0% found this document useful (0 votes)
43 views43 pages

Class and object

Class and object of C++ Programming

Uploaded by

bikash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views43 pages

Class and object

Class and object of C++ Programming

Uploaded by

bikash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Class and object

Kashiram Pokharel
Class
• A class is a collection of objects sharing common properties and relationship.
• It is a user defined data type and behave like built-in type of programming language. specifies what data
and what functions will be included in object of that class i.e. They allow variables and methods to be
isolated to specific objects instead of being accessible by all parts of the program.
• A Class is a user defined data-type which has data members and member functions. The data
components of the class are called data members and the function components are called member
functions.
• encapsulates data (attributes) and functions (behavior) into a single unit called classes. i.e Encapsulates
both its data and associated functions together
• Data members are the data variables and member functions are the functions used to manipulate these
variables and together these data members and member functions defines the properties and behavior
of the objects in a Class
• The data and functions of a class are intimately tied together. Class is a blueprint of real world objects. A
programmer can create any number of objects of the same class.
• Classes have the property of information hiding. It allows data and functions to be hidden, if necessary,
from external use. Classes are also referred to as user-defined data types.
• n C++, class is a group of similar objects. It is a template from which objects are created
• A class definition starts with the keyword class followed by the class name; and the class body, enclosed
by a pair of curly braces. A class definition must be followed by a semicolon.
Class: Declaration syntax
• syntax: • a class is a way to bind data and associated function together.
class class_name • it allows data and function to hidden if necessary for external use.
{ • defining a class means creating a user defined data type that
access-specifier: behaves as built in data.
variable declarations; • once a class has been declared we can create any number of
function declarations; object belonging to that class.
………………………………. • class contains both data and function . Data are called data
access-specifier: member and function are called member function.
variable declarations; • Generally data and function are defined in private section are not
function declarations; accessible out of the class.
………………………………… • data and function placed in public section are only accessible from
access-specifier: outside the class.
variable declarations; • the word private is optional . the data in function of class by
function declarations; default private.
………………………………..
};
Class Declaration:
Example:
class student
{
int rollno;
float marks;
public:
void insertdata(int a,float b);
void displaydata(void);
};
Access specifier/visibility level/access modifier:
• These specifiers control the access of the class members within the class. The
specifiers can be public, protected, and private.
• A class prevents the access of the data from the outside world using access
specifiers. It can set permissions to restrict the access of the data.
• Access specifiers define how the members (attributes and methods) of a class
can be accessed.
• Provides property of information hiding. It allows data and functions to be
hidden, if necessary, from external use.
Access specifier
• Private:
• When the private keyword is used to define a function or class, it becomes private.
• Private data and functions can only be accessed from within the member functions of that
class. However, friend classes and friend functions can access private members.
• By default all the members of a class would be private.
• Public:
• The public keyword, on the other hand, makes data/functions public. These are accessible
from outside the class.
• Can set and get the value of public variables without any member function
• Protected
• Protected access modifier is similar to that of private access modifiers, the difference is that
the class member declared as Protected cannot be accessed outside the class however they
are accessible by any derived class or subclass of that class.
• The main difference between private and protected is that protected inheritance allows
continued access to base class members whereas private inheritance prohibits the access of
those members.
Visibility modes:
Some example to create a class:
• Create a class which holds the information of student in a class and
operation which process that information
• Create a class to hold the page no , name, price and member function
which process there information about the book
• Create a class which holds hour, minute and second as a data and a
function to calculate time gap between two time period.
OBJECT:

• An object is the basic runtime entities in the OOPL, which have certain attribute
and behavior
• The attribute represent the data in a program, they have certain specific values
• behavior represents the method (function) which operate on that data
• Objects in C++ are analogous to real-world entities .An object is an instance of
class.
• It is the data item for user defined data type (class name) or variable of type class
• object oriented languages is combine both data and the function into a single
unit that operate on that data. such a unit is called an object
• When a class is defined, no memory is allocated but when it is instantiated (i.e.
an object is created) memory is allocated
• Declaration syntax:
class_name objects_name(variable name)
Defining Member functions:
• There are 2 ways to define a member function:
• Inside class definition
• Outside class definition
Defining Member Functions: Inside the class definition
• Replace function declaration by actual class student
function definition inside the class {
int roll_number;
• When a function is defined inside a float marks;
class, it is treated as an inline function. public:
void insertdata(int a, float b); //declaration
• Therefore, all the restrictions and //inline function
limitations that apply to an inline void displaydata(void) //definition inside the class
function are also application here {
cout<<roll_number<<"\n";
• all the member functions defined cout<<marks<<"\n";
inside the class definition are by }
default inline, but you can also make };
any non-class function inline by using
keyword inline with them.
Defining Member Functions: Outside the class definition
• The member functions that are declared inside a class have to be defined
separately outside the class.
• To define a member function outside the class definition we have to use
the scope resolution :: operator along with class name and function name.
• The general form of this definition is:
return-type class-name :: function-name(argument declaration)
{
Function body
}

• The symbol :: is called the binary scope resolution operator.


Accessing class member
• Objects communicate by sending and receiving messages Example:
• The private members cannot be accessed directly from class xyz
outside of the class. {
• The private data of class can be accessed only by the int x;
member functions of that class. int y;
public:
• The public member can be accessed outside the class from int z;
the main function };
• Syntax for calling a public member data is …….
object_name.member_variablename ; …….
Int main()
• The dot(.) operator is also called as “class member access {
operator.” is used to access the public member from the xyz p;
class object. p.x=10; //Error
• A member function can call another member function p.z=100; //Correct, z is public
directly, without using the dot operator }
void student::displaydata(void)
Example: {
cout<<"Roll Number: "<<roll_number<<"\n";
cout<<"Marks: marks: "<<marks<<"\n";
#include<iostream> }
#include<conio.h> int main()
using namespace std; {
class student int student_roll;
{ float student_marks;
int roll_number; student x; //Derive object x from student class
float marks; cout<<"Enter Roll Number:\n";
public: cin>>student_roll;
void insertdata(int a,float b); cout<<"Enter Marks:\n";
void displaydata(void); cin>>student_marks;
}; cout<<"Student info:\n";
void student::insertdata(int a, float b) x.insertdata(student_roll, student_marks); /*Call member functions
{ of class student*/
roll_number = a; x.displaydata();
marks = b; return 0;
} }
Some example to write a complete function
using class and object
• Write a program to add two number using class and object
• Write a program to enter basic detail information of employee and
increase their salary by 20% and display information with updated
salary.
• Write a program to enter two number and perform their arithmetic
operations.
Array of Objects
• Array can be of any data type.
• We can have arrays of variables that are of the type class. Such variables
are called arrays of objects.
• Like array of other user-defined data types, an array of type class can also
be created.
• The array of type class contains the objects of the class as its individual
elements.
• Thus, an array of a class type is also known as an array of objects.
• An array of objects is declared in the same way as an array of any built-in
data type
• Syntax
class_name array_name [size] ;
Array of Objects:
#include <iostream>
int main()
using namespace std;
class MyClass {
{ MyClass obs[4];
int x; int i;
public: for(i=0; i < 4; i++)
void setX(int i)
{
obs[i].setX(i);
x = i; for(i=0; i < 4; i++)
} cout << “value =" << i <<endl;
int getX()
{ }
return x;
}
};
Static data members:
• As you create an object from a class
• Each and every object will get a separate variables of that class
• Methods[functions] are being shared
• If the variable also be needed to be shared by each and every object in a
class then we can use Static Data members
• It is a variable which is declared with the static keyword, it is also
known as class member, thus only single copy of the variable creates
for all objects.
• Any changes in the static data member through one member function
will reflect in all other object’s member functions.
Static data member
• Static variables are normally used to maintain values common to entire class. If we create
the data member of a class is static then
1. It is initialized zero and only once when the first object of its class is created.
2. Only one copy of that member is created for the entire class and is shared by all the objects of that
class.
3. It is accessible only within the class, but its lifetime is the entire program
• The static variables are declared as follows:
static data_type data_member;
• Accessing static data member
class_name :: static_data_member;
class abc
• Defining a static member outside of that class: The type and {
scope of each static member must be defined outside the class static int c ;
-------
data_type class_name:: static data_member =Initial value; public:
• for above class abc C is defined as follows: ------
• int abc: : C ; C is automatically assigned to zero OR, ------
• int abc : : C=10 ; C is initialized 10 };
Example:
using namespace std;
class counter int main( ) {
{ counter c1, c2, c3 ; //count is initialized to zero
int n ; c1.showcount() ; // display count
static int count ; // static member variable
c2.showcount() ;
public:
void getdata (int number) c3.showcount() ;
{
n=number ; c1.getdata(10) ; //getting data into object c1
count ++ ; c2.getdata(20) ; //getting data into object c2
} c3.getdata(30) ; //getting data into object c3
void showcount( ) cout<< "value of count after calling" ;
{ cout<< "getdata function :" <<endl ;
cout<< "count:"<<count<<endl ; c1.showcount( ) ; //showcount
cout<<"value="<<n<<endl; c2.showcount( ) ;
} c3.showcount( ) ;
}; }
int counter :: count ;
Static member function
• If a member function is declared static that has following properties:
1. A static function can access to only other static member (static member
data and static member function) declared in the same class.
2. A static member function can be called even if no objects of the class
exist and the static functions are accessed using only the class name and
the scope resolution operator ::.
3. Declaration syntax :
static return_type function_name()
4. A static member function can be called using the same class
name(instead of its objects) as
classname : : function_name ;
#include <iostream.h>
class counter int counter : : count ;
{ void main( )
int a ; {
static int count ;
public:
counter c1, c2, c3 ; //assign Count=0
void assign( ) counter : : output( ) ;
{ c1.assign( ) ; c2.assign( ) ; c3.assign( ) ;
++ count ;
counter c4 ;
a = count ; }
void outputn( ) c4.assign( ) ;
{ counter : : output( ) ;
cout<< “A :”<<a<<endl ; c1.outputn( ) ; c2.outputn( ) ; OUTPUT:
} c3.outputn( ) ; count : 0
static void output( ) count : 4
c4.outputn( ) ; A:1
{
cout<< “count :”<<count<<endl ;
} A:2
A:3
} }; A:4
Nesting of Member function
• A member function can call another member function of the same class directly
without using the dot operator. This is called as nesting of member functions.
• Generally, the member function which is called by another member function is kept
private so that it cannot be called directly using the dot operator
using namespace std
class nest void disp_num()
{ {
int a; int sq=square_num(); //nesting of member function
int square_num( ) int cu=cube_num(); //nesting of member function
{ cout<<”\nThe square of “<<a<<” is ” <<sq;
return a* a;
} cout<<”\nThe cube of “<<a<<” is ” <<cu;
public: }
void input_num( ) };
{ int main()
cout<<”\nEnter a number ”; {
cin>>a; nest n1;
} n1.input_num();
int cube_num( ) n1.disp_num();
{ return 0;
return a* a*a;
} }
This Pointer:
• In c++ this is a keyword ,this represents an object that invokes a member
function. It is automatically passed to a member function when it is called.
• whenever any object called its member function this pointer is automatically
set and contains the address of that object.
• The pointer acts as an implicit argument to all the member function. One
important application of this is to return the object ,it points to as follows.
• The “this‟ pointer is passed as a hidden argument to all non-static member
function calls and is available as a local variable within the body of all non-static
functions.
• Usually, this pointer is used when local variable’s name is same as member’s
variable name
return *this;
Example: void display(void)
{
#include<iostream> float c;
c=x+y;
#include<conio.h>
cout<<"x = "<<x<<endl;
using namespace std; cout<<"y = "<<y<<endl;
/* local variable is same as a member's name */ cout<<"Addition of x and y = "<<c;
class thisPointer }
{ };
int x; int main()
int y; {
public: thisPointer tp;
void set_value (int p, int q) tp.set_value(10,20);
tp.display();
{
this->x =p;
getch();
this->y = q; return 0;
} }
Passing object as function argument:
• Like other variable ,the object can be used as a function argument .this
can be done by two method:
• pass by value
• pass by reference
• in pass by value a copy of entire object is passed in the function and
• in pass by reference only the address of the object is transferred to the
function .
• when an address of object is passed the called function works directly on the
actual objects used in the call and
• change made to the object inside the function will reflect in the actual object.
Mechanism:
• To pass an object as an argument we
write the object name as the argument
while calling the function the same way
we do it for other variables.
• Syntax:
function_name(object_name);
• The function is called by one object and
takes another as an argument.
• Inside the function, the integer value of
the argument object is added to that on
which the ‘add’ function is called. In this
method, we can pass objects as an
argument and alter them.
Example: void complex ::showdata()
{
cout<<real<<"+"<<img<<"i"<<endl;
#include <iostream>
}
using namespace std;
class complex void complex::add(complex c1,complex c2)
{ {
int img,real; real=c1.real +c2.real;
public: img=c1.img+c2.img;
void inputdata(); }
void showdata(); int main()
void add(complex,complex); {
};
complex x,y,z;
void complex::inputdata()
x.inputdata();
{
y.inputdata();
cout<<"enter real part "<<endl;
cin>>real; z.add(x,y);
cout<<"enter imaginary part"<<endl; x.showdata();
cin>>img; y.showdata();
} z.showdata(); }
Returning Object From Function:
• A function can also return objects either by value or by reference.
• When an object is returned by value from a function, a temporary
object is created within the function, which holds the return value.
• This value is further assigned to another object in the calling function.
• The syntax for defining a function that returns an object by value is
class_name function_name (parameter_list) {
// body of the function
}
• Function calling syntax:
object name=function_name(argument);
void complex ::showdata()
#include <iostream> {
using namespace std; cout<<real<<"+"<<img<<"i"<<endl;
class complex }
{
complex complex::add(complex c2)
int img,real;
public: {
void inputdata(); complex temp; int main()
void showdata(); temp.real=real +c2.real; {
complex add(complex); complex x,y,z;
temp.img=img+c2.img;
}; x.inputdata();
return temp; y.inputdata();
void complex::inputdata()
{ } z=x.add(y);
cout<<"enter real part "<<endl; x.showdata();
y.showdata();
cin>>real;
z.showdata();
cout<<"enter imaginary part"<<endl;
return 0;
cin>>img;
}
Friend functions:
• The outside functions can’t access the private data of a class. But there could
be a situation where we could like two classes to share a particular member.
• C++ allows a mechanism, in which a non member function can access the
private data of a class. this can be done by declaring a non member function
as a friend to a class whose private data is to be accessed.
• A C++ friend functions are special functions which can access the private
members of a class. They are considered to be a loophole in the Object
Oriented Programming concepts, but logical use of them can make them
useful in certain cases
• A friend function is a function that is specified outside a class but has the
ability to access the class members’ protected and private data.
• A friend can be a member’s function, function template, or function, or a class
or class template, in which case the entire class and all of its members are
friends.
• The member function of one class may be the friend function of another class
Feature of Friend functions:
• Friend functions have the following properties:
• Friend of the class can be member of some other class.
• Friend of one class can be friend of another class or all the classes in one
program, such a friend is known as GLOBAL FRIEND.
• Friend can access the private or protected members of the class in which they
are declared to be friend, but they can use the members for a specific object.
• Friends are non-members hence do not get “this” pointer.
• Friends, can be friend of more than one class, hence they can be used for
message passing between the classes.
Friend function:
• Friend function is not in the scope of the class in which it has been
declare as friend. So friend function cannot be called with the help of
object of that class.
• Friend function can be invoked like a normal function with out any
help of any object.
• Friend can be declared anywhere (in public, protected or private
section) in the class
• Friend function can access many object of many class in which it has
been declared as friend.
• usually , friend function has object as argument
Example:
using namespace std;
class sample float mean (sample s)
{ {
int a; return float (s.a + s.b)/2.0;
int b; // accessing private data with help of object
of that class
public: }
void setvalue() int main()
{
{
a=25;
b=40; sample X; //object X
} X.setvalue();
friend float mean (sample s); //declaration of cout<<mean (X);// call to friend
friend function in function
public part return 0;
};
}
class sample2
{
Example 2 int i;
public:
void setvalue()
{
i=15;
}
using namespace std; friend float mean(sample1 s1,sample2 s2); /* Declaration of friend
class sample2; /*called forward declaration */ function in class sample1 */
class sample1 };
float mean(sample1 s1 , sample2 s2) /* Definition of friend
{ function */
int a; {
public:
void setvalue()
return (s1.a+s2.i)/2.0;
{ }
a=10; main()
} {
friend float mean(sample1 s1,sample2 s2); sample1 x;
}; x.setvalue();
sample2 y;
y.setvalue();
cout<<mean(x,y);/* calling of friend function without help of any object
*/
getch();
return 0;
}
Summary:
• In special cases when a class’s private data needs to be accessed directly without using objects of that
class, we need friend functions.
• They are also used in operator overloading because they are more intuitive. The binary arithmetic
operator that is commonly used can be overloaded the friend function way. Go ahead and check out
operator overloading using a friend function for more information.
Special features of friend functions:
• A friend function does not fall within the scope of the class for which it was declared as a friend.
Hence, functionality is not limited to one class.
• The friend function can be a member of another class or a function that is outside the scope of the
class.
• A friend function can be declared in the private or public part of a class without changing its meaning.
• Friend functions are not called using objects of the class because they are not within the class’s scope.
• Without the help of any object, the friend function can be invoked like a normal member function.
• Friend functions can use objects of the class as arguments.
• A friend function cannot explicitly access member names directly. Every member name has to use the
object’s name and dot operator.. For example, Doctor.pay where pay is the object name.
• member functions of one class can also be made friend functions of another class by defining the
function using the scope resolution operator as shown below:
class className1{
// Other Declarations
int functionName1(); // member function of className1
};

class className2
{
// Other Declarations
friend int className1::functionName(); //The functionName1() is a friend of className2
};
Friend Class
• We know that member of one class can not access the private data of
other class. Some time it is needed that we want to make available
private data of one class to other class. In such case we need to make
one class to a friend of other class.
• A class can also be declared to be the friend of some other class.
• When we create a friend class then all the member functions of the
friend class also become the friend of the other class.
• This requires the condition that the friend becoming class must be first
declared or defined (forward declaration).
• It is a member function of one class and uses object of other class as
arguments so the function has to be called using corresponding class
object and other class object as arguments.
using namespace std; class Second
class second; {
class first public:
{ void change( first &obj, int x )
private: {
int Secret; obj.Secret = x;
friend class Second; // Declare a }
friend class };
public:
first() int main()
{ {
Secret=4; first obj1;
} Second obj2;
void printMember() obj1.printMember();
{ obj2.change(obj1, 5 );
cout << Secret << endl; obj1.printMember();
} }
};
*******************Thank You**************************

You might also like