You are on page 1of 68

Class & Objects

• C++ offers another user-defined data type known


class which is the most important feature of the
object-oriented programming.

• A class can declare and define both data and


functions that are hidden from the external use.

• The binding of data and functions together into a


single class type variable is known as
encapsulation.
The general form of declaration of a
class:
class class_name
{
private:
variable declaration ; // data members
function declaration ; // member functions
public:
variable declaration ; // data members
function declaration ; // member functions
};
Cont.
• The specifier starts with the keyword class, followed
by the class_name.

• The body of the class is delimited by the braces { }


and terminated by the semicolon ( ; ).

• The variables and functions within the body of the


class are collectively known as members.

• The data or variables declared within the class are


known as data members, while the functions
declared/defined within the class are known as
member functions.
private and public keywords
• The data members and the member functions are usually grouped
under two sections: private and public, which are known as the access
specifiers.

• These keywords are followed by the colon ( : ).

• If no specifier is used, then the members are private, by default.

• The members (data and functions) declared in the private mode can be
accessed only from within the class, while the members declared in the
public mode can be accessed from outside the class also.

• The private data member and the private member functions can only
be accessed by the member functions of the class.

• Generally, it is common practice to declare the data members in the


private mode and member functions in the public mode. Thus, the data
is hidden, and is safe from the accidental manipulations. On other hand,
the functions that operate on the data are declared in the public mode,
so that they can be accessed from outside the class. However, there
may arise some situations when one needs to use private functions and
public data
Fig: Accessibility of public and private members
private:
Data member1
Not accessible from
outside the class
Member
function1

public:
Data member2

Accessible from
outside the class
Member
function2

Notations used:
Indicates that the member (data or function) is not accessible
Indicates that the member (data or function) is accessible
Example:
#include<iostream.h>
class Rectangle
{
float length, breadth ; // Data members within the class rectangle,
// which are private by default
public:
void enterdata(void) ; // Member function declarations within the
void disparea(void) ; // class rectangle, which are declared as public
};
//******************Member Function Definitions**************
void Rectangle :: enterdata(void)
{
cout << "\n Enter the length of the rectangle: " ;
cin >> length ;
cout << "\n Enter the breadth of the rectangle: " ;
cin >> breadth ;
}
void Rectangle :: disparea(void)
{
float area = length * breadth ;
cout << "\n The area of the rectangle is = " << area << endl ;
}
Cont.
//*****************Main Function*****************************
void main(void)
{
Rectangle r1, r2 ; // a1 and a2 are objects of the
// user-defined type rectangle
cout << "\n First rectangle-->\n" ;
r1.enterdata( ) ; // Call Member Functions
r1.disparea( ) ;

cout << "\n Second rectangle-->\n" ;


r2.enterdata( ) ; // Call Member Functions
r2.disparea( ) ;
}
Defining member functions
There are two ways to define the member
functions:
• Outside the class.
• Inside the class.
• Normally, only small functions are defined
inside the class definition. However, it is
good programming practice to define the
member functions outside the class.
Defining member function outside the class:
• Member functions that are declared inside the class have to be defined separately outside
the class.

• The syntax of a member function definition is:


return_type class_name :: function_name(arguments)
{
Body of the function ;
}

• Here, double colon (::), is the scope resolution operator.


• The combination of class_name and :: tells the compiler that the member
function function_name belongs to the class class_name.

• For example, in the previous program, the member functions are defined outside
the class as:

void Rectangle :: enterdata(void)


{
cout << "\n Enter the length of the rectangle: " ;
cin >> length ;
cout << "\n Enter the breadth of the rectangle: " ;
cin >> bredth ;
}
Defining the member functions inside the class:

• The general form of defining the member


function inside the class is:

return-type function-name(arguments)
{
Function body ;
}
Example:

# include<iostream.h>
class Rectangle // Name of the class
{
float length, breadth ; // Data members which are private by default

// Definition of the member functions within the class***********


public:
void enterdata(void)
{
cout << "\n Enter the length of the rectangle: " ;
cin >> length;
cout << "\n Enter the bredth of the rectangle: " ;
cin >> breadth;
}
void disparea(void)
{
float area = length * breadth ;
cout << "\n The area of the rectangle is: " << area << endl ;
}
} ; // Class definition terminated by the semicolon ( ; )
Creating Objects
• After defining the class, one can declare objects of that
class in the main( ) function.

• The syntax for declaring an object is:


class_name obj-1, obj-2, -------,obj-N ;

• For example, in the previous programs, the first


statement in the main( ) i.e.
Rectangle a1, a2 ;
defines two objects of class Rectangle. Defining an
object is similar to defining a variable of any data
type. The space is also set aside for the object in the
memory, like other variables.
Cont.
• Objects can also be created by placing their names immediately
after the closing brace, as in the case of structures.

• For example, the class definition

class Rectangle
{
private:
int length, breadth ;
public:
void enterdata( ) ;
void disparea( ) ;
} a1, a2 ;

would create objects a1 , a2 of type Rectangle. Generally, the objects


are declared close to the place where they are used.
Calling members
• Only an object of a class can access the members of that class. The
syntax for calling a member of the class is:

object_name . data_member ; // For calling the data member


// of the class

object_name . member function(actual argumemnts ) ; // For calling


// the member function of the class

• The dot operator ( . ) is known as class member access operator.


For example, in the program, the statements that call the member
functions are given as:

a1.enterdata( ) ;
a1.disparea( ) ;
Cont.
• Note that the objects of a class can access only those
members of the class that are declared in public mode.

• The private members of a class cannot be accessed by


the objects of that class.

• Thus, one cannot access the data members length and


breadth, of the above programs: using the notation:
a1.length ; // Not valid
a2.breadth ; // Not valid

because they have been declared in the private mode.


Since, the member functions enterdata( ) and disparea( )
are declared in the public mode, they can be accessed by
the objects of that class.
Extension to Structures in C++

• So far it has been discussed that structures are used


to group data and classes are used to group both data
and functions.

• In C++, the structures can also be used to group both


data and functions, like the classes.

• The only difference between structure and class is that


in a structure the members (data and function) are
public by default, while in a class the members are
private by default.
The following declarations of the class and
structure accomplish the same task.

class Rectangle struct Rectangle


{ {
// private by default // public by default
float length, breadth ; void enterdata(void) ;
void disparea(void) ;
public:
void enterdata(void) ; private:
void disparea(void) ; float length, breadth ;

}; };

Thus in C++, a structure can be thought of as a class. However, it is general


practice to use structure to group data, and classes to group both data and
functions.
Initialization of the objects: The objects can be initialized by using the
member function to which the value is passed to be set up.
// This program illustrates the initialization of the object
#include<iostream.h>
class Rectangle
{
private:
float length, breadth ;
public:
void initialize(float l, float b) ;
void disparea(void) ;
} ; // End of the class definition

//***********Member function definitions**************


inline void Rectangle :: initialize(float l, float b)
{
length = l ;
breadth = b ;
}
inline void Rectangle :: disparea(void)
{
float area = length * breadth ;
cout << "\n\t The area of the rectangle is: " << area ;
}
Cont.
void main(void)
{
Rectangle a1, a2 ; // Declaration of the objects a1 & a2 of type rectangle

cout << "\n First rectangle-->\n" ;

a1.initialize(10.5, 8.4) ; // Initialization of the first object

a1.disparea( ) ;

cout << "\n\n Second rectangle-->\n" ;

a2.initialize(12.6, 10.2) ; // Initialization of the second object

a2.disparea( ) ;
}
Constructor
• A constructor is a special kind of member function that allows one to
set up values while defining the objects, without need to make a
separate call to a member function.

• A constructor is executed automatically whenever an object is created.


Remember that the class and the constructor(s) in it must have
same names. This is how the compiler knows that the member function
is a constructor.

• Moreover, no return type is used for the constructor (not even void).
Since, the constructor is called automatically when an object is created;
returning a value would make no sense.

• The constructor that does not accept any parameter is called the
default constructor.

• On other hand, the constructor that can take arguments is called


parameterized constructor.
The general form of declaration of the constructor is:

class class_name
{
private:
data_member ;
public:
class_name(argument_list) ; //
Constructor
};
Example

// This program illustrates the use of the constructors in the class


#include<iostream.h>
class Rectangle
{
private:
float length ;
float breadth ;
public:
Rectangle( ) // Default constructor, without any argument
{ }
Rectangle(float l, float b) // Constructor with two arguments
{
length = l ;
breadth = b ;
}
void Enter_lb(void)
{
cout << "\n\t Enter the length of the rectangle: " ;
cin >> length ;
cout << "\t Enter the breadth of the rectangle: " ;
cin >> breadth ;
}
void Display_area(void)
{
cout << "\n\t The area of the rectangle = " << length*breadth ;
}
} ; // End of the class definition
Cont.

void main(void)
{
Rectangle r1 ; // Invokes the first constructor without any argument
cout << "\n First rectangle-------->\n" ;
r1.Enter_lb( );
r1.Display_area( );
cout << "\n\n Second rectangle------->\n" ;
rectangle r2(5.6, 3.5); //Invokes the second constructor with two
// arguments
r2.Display_area( );
}
Overloaded constructors

• An important thing to be noticed in the previous program, is


that two constructors with the same name i.e. rectangle( )
are used. These constructors can be called as overloaded
constructors.

• Constructors obey the same overloading rules, as do other


functions.
Implicit constructor
• Let us look at the first constructor again.
Rectangle( )
{
// Empty body
}
• This constructor is defined with the empty
body and is also known as implicit
constructor.
• This constructor is used to create objects
without any initial values, as discussed
earlier.
Copy constructor
The parameters of a constructor can be of any type
except that of the class to which it belongs.

For example,
class Rectangle
{
………
………
public:
Rectangle(Rectangle r) ; // This is not valid
};

is not valid in C++, because the compiler will complain that


it is out of memory.
Cont.
• When an argument is passed by value, a copy of it is constructed by
the copy constructor.
• The copy constructor calls itself over and over until the compiler
runs out of memory.
• So, in the copy constructor, the argument must be passed by
reference, which creates no copies.
• However, a constructor can accept a reference to its own class as a
parameter. For example,
class Rectangle
{
…………
…………
public:
Rectangle(Rectangle & r) ; // This is valid
}
is valid in C++. Such type of constructor is known as copy
constructors, which is used to copy its argument into a new object.
Example:
#include<iostream.h>
class Rectangle
{
private:
float length, breadth ;
public:
Rectangle( ) // First constructor without any argument
{ length = 0.0 ; breadth = 0.0 ;}
Rectangle(float l, float b) // Second constructor with two arguments
{ length = l ;breadth = b ; }
Rectangle(Rectangle & r) // Third constructor which is a copy constructor
{
length = r.length ;
breadth = r.breadth ;
}
void Enter_lb(void)
{
cout << "\n\t Enter the length of the rectangle: " ; cin >> length ;
cout << "\t Enter the breadth of the rectangle: " ; cin >> breadth ;
}
void Disp_area(void)
{
cout << "\n\t\t Area of the rectangle = " << (length*breadth) ;
}
} ; // End of the class definition
Cont.
void main(void)
{
Rectangle r1 ; // Invokes the second constructor without any argument

cout << "\n First constructor without any argument is invoked******\n" ;

r1.Enter_lb( );

r1.Disp_area( );

Rectangle r2(7.5, 3.6); // Invokes the second constructor with two arguments

cout << "\n\n Second constructor with two argument is invoked*****\n" ;

r2.Disp_area( );

Rectangle r3(r2); //Invokes the third constructor which is a copy constructor

cout << "\n\n Third constructor which is a copy constructor is invoked\n" ;

r3.Disp_area( );
}
Destructor
• A constructor initializes an object. In other words, it creates the
environment in which the member functions operate. Sometimes,
creating that environment involves acquiring a resource- such as a file,
a lock, or some memory that must be released after use. Thus, some
classes need a function that is guaranteed to be invoked when an object
is destroyed in a manner similar to the way a constructor is guaranteed
to be invoked when an object is created. Such functions are called
destructors.

• They typically clean up and release resources.

• The most common use of a destructor is to deallocate memory that was


allocated for the object by the constructor.

• A destructor has the same name as the constructor but proceeded by a


tilde (~). Like constructors, destructors do not have a return value and
don’t take any argument.

• It is good practice to declare a destructor in the program since it


releases memory space for future use.
Objects as function arguments
• There are two methods of passing the objects: pass by
value and pass by reference.

• When an object is passed by value, a copy of this object


is passed to the function and any changes made to the
object inside the function do not affect the object used to
call the function.

• On other hand, when the object is passed by reference,


the called function works directly on the actual object
used in the call. The pass by reference method is more
efficient since it requires to pass only the address of the
object and not the entire object.
Example:
// This program illustrates the passing of objects as arguments
#include<iostream.h>
class Complex
{
float real, imaginary ;
public:
Complex( )
{ real = 0.0; imagnary = 0.0 ; }
Complex(float r, float i)
{ real = r ; imaginary = i ; }
void enter_data(void)
{
cout << "\n Enter the real number: " ;
cin >> real ;
cout << " Enter the imaginary number: " ;
cin >> imaginary ;
}
void display_data(void)
{
if(imaginary >=0)
cout << "\n\t The complex number is: " << real << "+"
<< imaginary << " i" << endl ;
else
cout << "\n\t The complex number is: " << real
<< imaginary << " i" << endl ;
}
Cont.
void add_comp(Complex c1, Complex c2) ;
void mul_comp(Complex c1, Complex c2) ;
} ; // End of the class definition

void Complex :: add_comp(Complex c1, Complex c2)


{
real = c1.real + c2.real ;
imaginary = c1.imaginary + c2.imaginary ;
}
void Complex :: mul_comp(Complex c1, Complex c2)
{
real = (c1.real * c2.real)-(c1.imaginary * c2.imaginary) ;
imaginary = (c1.imaginary * c2.real)+(c1.real * c2.imaginary)
;
}
Cont.
void main(void)
{
Complex com1(- 5.3, 3.2), com2, com3, com4 ;
cout << "\n First complex number-->\n" ;
com1.display_data( ) ;
cout << "\n Second complex number-->\n" ;
com2.enter_data( ) ;
com2.display_data( ) ;
com3.add_comp(com1, com2);
cout << "\n Addition of two complex numbers-->\n" ;
com3.display_data( ) ;
com4.mul_comp(com1, com2) ;
cout << "\n Multiplication of two complex numbers-->\n" ;
com4.display_data( ) ;
}

Output:
First complex number
The complex number is: -5.3+3.2 i
Second complex number

Enter the real number: 7


Enter the imaginary number: 4.5

The complex number is: 7+4.5 i


Addition of two complex numbers
The complex number is: 1.7+7.7 i
Returning objects from the functions
#include<iostream.h>
class Complex
{
private:
float real, imaginary ;
public:
Complex( ) // Default Constructor
{ }
Complex(float r, float i) // Constructor with two arguments
{
real = r ;
imaginary = i ;
}
void enter_data(void) // Function to get the real and imaginary parts
{
cout << "\n Enter the real part of the complex number: " ;
cin >> real ;
cout << " Enter the imaginary part of the complex number:
";
cin >> imaginary ;
}
Cont.
Complex add_comp(Complex c) /* Member function declarative with
arguments and return value of type complex */
{
Complex temp ; // temporary object
temp.real = real + c.real ; //adds the real parts of
// two complex numbers
temp.imaginary = imaginary + c.imaginary ; // adds the imaginary
// parts of two complex numbers

return temp ;
}
void display_data(void)
{
if(imaginary >=0)
cout << "\n\t The complex number is: " << real << "+"
<< imaginary << " i" << endl ;
else
cout << "\n\t The complex number is: " << real
<< imaginary << " i" << endl ;
}
}; // End of the class definition
Cont.
void main()
{
Complex c1, c2(4.5, -3.2), c3 ;
c1.enter_data( );
cout << "\n First complex number***********" ;
c1.display_data( );
cout << "\n Second complex number**********" ;
c2.display_data( );
c3 = c1.add_comp(c2);
cout << "\n The sum of the above two complex numbers********";
c3.display_data( );
}
Output:
Enter the real part of the complex number: 2.5
Enter the imaginary part of the complex number: 3.8
First complex number***********
The complex number is: 2.5+3.8 i
Second complex number*********
The complex number is: 4.5-3.2 i
The sum of above two complex numbers**********
The complex number is: 7+0.6 i
Passing of objects by reference:
// This program illustrates the passing of the object arguments by reference.
#include<iostream.h>
class Complex
{
private:
float real, imaginary ;
public:
Complex( )
{
real = 0.0 ;
imaginary = 0.0 ;
}
Complex(float r, float i)
{
real = r ;
imaginary = i ;
}
void enter_data(void)
{
cout << "\n Enter the real number: " ;
cin >> real ;
cout << "\n Enter the imaginary number: " ;
cin >> imaginary ;
}
Cont.

void add_comp(Complex& c1, Complex& c2) /* Arguments are passed


by reference */
{
real = c1.real + c2.real ;
imaginary = c1.imaginary + c2.imaginary ;
}
void display_data(void)
{
if (imaginary >= 0)
cout << real << "+" << imaginary << "i" << endl ;
else
cout << real << imaginary << "i" << endl ;
}
}; // End of the class definition
Cont.
void main(void)
{
Complex com1(3.5, 5.6), com2 ;

cout << "\n The first complex number is: " ;


com1.display_data( );

com2.enter_data( );
cout << "\n The second complex number is: " ;
com2.display_data( );

Complex com3 ;
com3.add_comp(com1, com2);
cout << "\n The sum of the two complex numbers is: " ;
com3.display_data( );
}
Output:
The first complex number is: 3.5+5.6i
Enter the real number: 4.5
Enter the imaginary number: 7.5
The second complex number is: 4.5-7.5i
The sum of two complex numbers is: 8-1.9i
Constructors with default arguments

• The member functions of a class may also


contain the arguments with the default values.

• Only the trailing argument can have default


values i.e. from right to left.
Example
#include<iostream.h>
class S_Interest // Class Name
{
private:
float p_amt ; // Principal amount
int time, rate ; // time period and rate of interest
public:
S_Interest( ) // Defluat constructor
{ }

S_Interest(float p, int t, int r = 5) /* Constructor with default


argument r = 5 */
{
p_amt = p ;
time = t ;
rate = r ;
}
void Display_si(void)
{
cout << "\n The Simple Interest is: “; <<
(p_amt * time * rate/100) ;
}
}; // End of the class definition
Cont.

void main(void)
{
S_Interest s(5995.75, 5);
s.Display_si( );
}

Output:

The Simple Interest is: 1498.94


Inline functions: When the compiler sees a function call, it normally

generates a jump to the function. At the end of the function, it jumps back
to the instruction following the call. While this sequence of events may save
memory space, it takes some extra time.

void main()
{ void display()
display( );
…………. {
if (imaginary >= 0)
……….....
cout << “\n complex number is: “ << cout << real << “+” << imaginary <<
display( ); “i” ;
else
…………..
cout << “\n complex number is: “ <<cout << real << imaginary << “i” ;
………….. }
display( );
…………..
………….. Fig: Repeated code placed in function
}
Cont.

• To save the execution time in short functions, you may select to put
the code in the function body directly in line with the code in the
calling program.

• In other words, each time there is a function call in the source file,
the actual code from the function is inserted instead of a jump to the
function.

• When the program is compiled, the function body is actually inserted


into the program whenever a function call occurs.
void main( )
{
if (imaginary >= 0)
cout << “\n complex number is: “ << cout << real << “+” << imaginary <<
“i” ;
else
cout << “\n complex number is: “ <<cout << real << imaginary << “i” ;
…………………………………….
…………………………………….
if (imaginary >= 0)
cout << “\n complex number is: “ << cout << real << “+” << imaginary <<
“i” ;
else
cout << “\n complex number is: “ <<cout << real << imaginary << “i” ;
…………………………………….
…………………………………….
if (imaginary >= 0)
cout << “\n complex number is: “ << cout << real << “+” << imaginary <<
“i” ;
else
cout << “\n complex number is: “ <<cout << real << imaginary << “i” ;
…………………………………….
…………………………………….
}
Figure: Repeated code placed inline
Macros in C

#define CUBE(x) (x*x*x)


#include<stdio.h>
void main()
{
int a , c;
printf(“\n Enter any number:”);
scanf(“%d”, &a);
c = CUBE(a);
printf(“\n The cube of a is %d”, c );
}
Inline functions (cont.)

• The compiler must have seen the function


definition (not just the declaration) before it gets
to the first function call. This is because it must
insert the actual code into the program, not just
the instruction to call the function.

• Sometimes the compiler will ignore the request


and compile the function as a normal function. It
might decide the function is too long to be inline.
Example:
inline void sum(int a, int b) // inline function definition
{
int c = a+b;
cout << “\n The sum of numbers is: ” << c ;
}
void main()
{

int x, y ;
cout << “\n Enter the values of x and y:” ;
cin >> x >> y;
sum(x, y);
}
Example:
// This program illustrates the use of the inline functions
#include<iostream.h>
class Rectangle
{
private:
float length ;
float breadth ;
public:
Rectangle( ) // Default constructor, without any argument
{ length =0; breadth = 0; }
Rectangle(float l, float b) // Constructor with two arguments
{ length = l ; breadth = b ; }
void Enter_lb(void)
{
cout << "\n\t Enter the length of the rectangle: " ;
cin >> length ;
cout << "\t Enter the breadth of the rectangle: " ;
cin >> breadth ;
}
void Display_area(void)
{
cout << "\n\t The area of the rectangle = " <<
length*breadth ;
}
} ; // End of the class definition
Eg: Defining the inline functions outside the class
#include<iostream.h>
class Rectangle
{
private:
float length ;
float breadth ;
public:
Rectangle( ) ; // Default constructor, without any argument

Rectangle(float , float) ; // Constructor with two arguments

void Enter_lb(void) ;

void Display_area(void) ;

} ; // End of the class definition


Cont.

Rectangle :: Rectangle( ) // Default constructor, without any argument


{
length =0; breadth = 0;
}
Rectangle :: Rectangle(float l, float b) // Constructor with two arguments
{
length = l ; breadth = b ;
}
inline void Rectangle :: Enter_lb(void)
{
cout << "\n\t Enter the length of the rectangle: " ;
cin >> length ;
cout << "\t Enter the breadth of the rectangle: " ;
cin >> breadth ;
}
inline void Rectangle :: Display_area(void)
{
cout << "\n\t The area of the rectangle = " << (length*breadth) ;
}
static data member
 The data members in a class can be defined as static.

 A static member variable is available only within the class, but it continues to live
till the time program execution does not come to an end.

 Note that the type and scope of each static member variable must be defined
outside the class definition. This is necessary because the static data members
are stored separately rather than as a part of an object.

 They are also known as class variables, as they are associated with the class
itself rather than with any class objects.

 The syntax for defining a static variable is:


static data-type class_name :: variable_name ;

 By default, a static member variable is initialized to zero. However, some initial


value can also be assigned to the variable.

 Static member variables are normally used to maintain the values common to the
entire class. For example, there may be a situation when an object is required to
know how many other objects of its class are in existence.
Example
// This program illustrates the use of the static member variable in a class
#include<iostream.h>
class Objcount
{
private:
static int count ; // Member Variable declared as static
public:
Objcount( ) // Constructor
{
count++ ;
}
void display(void)
{
cout << "\n cout = " << count ;
}
};
//*********Definition of the Static Member Variable count***************
int Objcount :: count ; // count is initialized to 0 by default

void main(void) Output:


{
count = 3
Objcount o1, o2, o3 ;
o1.display( ) ; count = 3
o2.display( ) ; count = 3
o3.display( ) ;
}
Example2:
#include<iostream.h>
class StaticSample
{
private:
int count ;
static int staticcount ; // static data
public:
StaticSample( ) // Default constructor, without any argument
{ count = 0;
count++ ;
staticcount++ ;
}
void display(void)
{
cout << "\n\tcount = " << count ;
cout << "\n\tstaticcount = "<< staticcount <<
endl;
}

} ; // End of the class definition


Cont.
int StaticSample :: staticcount = 0 ; // Definition of static data

void main( )
{
StaticSample s1
cout << “\nAfter defining first object of StaticSample class---->\n”;
s1.display();

StaticSample s2 ;
cout<<"\nAfter defining second objects of StaticSample class---->\n";

s1.display();
s2.display();

StaticSample s3;
cout << "\n\n After defining third object of StaticSample class---->\n";
s1.display();
s2.display();
s3.display();
}
Cont.
Output:
After defining one object of StaticSample class---->
count = 1
staticcount = 1

After defining two objects of StaticSample class---->


count = 1
staticcount = 2

count = 1
staticcount = 2

After defining three objects of StaticSample class---->


count = 1
staticcount = 3

count = 1
staticcount = 3

count = 1
staticcount = 3
staticcount=3

s1 s2 s3
count=1 count =1 count =1
Static member function:
• Like static member variables, the member functions can
also be declared as static.

• A static member function can access only the other static


member functions or static data, declared in the same class.

• A static member function is not part of the objects of a class.

• The static member functions can be called using the


class name instead of its objects.

• The syntax for calling a static member function is:


class_name :: function_name( ) ;
Example
// This program illustrates the use of the static member functions
#include<iostream.h>
class Test
{
private:
static int total ; // static data member
public:
Test( )
{
total++ ;
}
static void display(void) // static member function
{
cout << "\n total = " << total <<
endl ;
}
}; // End of the class definition
Cont.
int Test :: total = 0 ; // Initialize total before main( )
void main(void)
{
cout << "\n When no object is created************** " ;
Test :: display( ); // Accessing static member function

Test obj1, obj2, obj3 ;

cout << "\n When three objects have been


created******" ;
Test :: display( ); // Accessing static member function
} Output:
When no object is created*********************
total = 0
When three objects have been created******
total = 3
Friend function

• Friend function can access the private


data.
• Friend function acts as an interface
between two different classes.
• The syntax for declaration of the friend
function is:
friend return_type function_name(argument(s) );
Example: Violating the concept of data hiding using friend
function
class Sample
{
int value;
public:
Sample()
{ value = 5; }
friend void funct(Sample); // Declaration of friend function
};

void funct(Sample s) // Friend function Definition


{
cout << “\n The value is: “ << s.value;
}
void main()
{
Sample samp;
Output:
func(samp);
} The value is: 5
Example: Interface between two different classes
#include<iostream.h>
class Two; // Forward declaration of class
class One
{
int o ;
public:
One( )
{ o = 5; }
friend void sum(One, Two); //Friend function
};

class Two
{
int t;
public:
Two( )
{ t = 10; }
friend void sum(One, Two); //Friend function
};
Cont.
void sum(One one, Two two) // Friend function definition
{
int s = one.o + two.t ;
cout << “\n The sum = “ << s;
}
void main()
{
One o1;
Two t2;
sum(o1, t2);
}

Output:
The sum = 15
The const keyword
• To prevent the normal variables from
being modified.

• On function arguments to keep a function


from modifying a variable passed to it by
value or by reference.

• On member functions of a class.

• On member function arguments.


const member function
• A constant member function guarantees that it
will never modify any of its class’s member data.

• To make a member function constant, the


keyword const is placed after the declarative but
before the function body.

• If the member function is declared inside the


class but defined outside it, then it is necessary
to use const in the declaration as well as
definition.
Example
#include<iostream.h>
#include<conio.h>
class Sample
{
private:
int data;
public:
Sample(int d = 0)
{ data = d; }
void ChangeData( ) const // constant member function
{ data = data + 10; / * This is invalid */ }
void DisplayData()
{ cout << “\n data = “ << data; }
};
void main()
{
Sample s(10) ;
s.ChangeData() ; Compiler error:
s.DisplayData() ; Cannot modify a const object
}

You might also like