Department of Computer Engineering
Learning Material
Class: CO3K Course: Object Oriented Programming
Unit 2
Inline Function:
Functions are used to avoid repetitive task and also to save some memory space.
However each time a function is called, it takes a lot of extra time in executing a series
of instructions for task such as jumping to the function, saving registers, pushing
arguments into the stacks and returning to the calling function.
To eliminate these problems C++ provides a new feature called inline function.
Definition: An inline function is a function that is expanded in line when it is
invoked. That is the compiler replaces each function call with the corresponding
function code.
The functions defined inside the class definition are treated as inline.
One can define the function outside the class and still make it inline using inline key
word. The memory space for object is allocated when they are declared and not when
the class is specified.
Advantages of Inline functions:
o In line expansion makes a program run faster.
Disadvantage of inline functions:
o Takes more memory
Some of the situations where inline expansion may not work are:
o For functions returning values if a loop, a switch or a go to exists.
o For functions not returning values, if a return statement exists.
o If functions contain static variables.
o If inline functions are recursive
Syntax : inline return- data-type function-name ( Argument declaration)
{
function Body
}
Example:
inline double cube ( double a)
{
return ( a * a * a);
}
Inline function-example (outside):
class student
{
int rollno ;
public :
void getdata (void );
};
inline void student :: getdata (void ) // defined outside the class but still inline
{
cout << “ENTER ROLL NO : “;
cin >> rollno;
}
STATIC DATA MEMBER:
A data member of a class can be qualified as static . The properties of a static member
variable are similar to that of a static variable. A static member variable has contain
special characteristics.
Static Data Member Characteristics:-
1. It is initialized to zero when the first object of its class is created. No other
initialization is permitted.
2. Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
3. It is visible only with in the class but its life time is the entire program. Static variables
are normally used to maintain values common to the entire class.
4. The static data members are associated with the class rather than with any object
,that is why they are sometimes called class variables.
5. To access static data always use name of the class instead of object with scope
resolution operator (::). Eg: item :: count;
Where item name of the class and the count is is the static data member.
6. The type and the scope of each static variable must be declared
int item :: count
7. This type of variable is normally used to maintain values, which is common to entire
class.
Example: A static data member can be used as a counter that records the occurrence of
all the objects.
int item :: count; // definition of static data member
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.
Example:
#include<iostream.h>
class item
{
static int count; //count is static
int number;
public:
void getdata(int a)
.{
number=a;
count++;
}
void getcount(void)
{
cout<<”count:”;
cout<<count<<endl;
}
};
int item :: count ; //count defined
int main( )
{
item a,b,c;
[Link]( );
[Link]( );
[Link]( ):
[Link]( ):
[Link]( );
[Link]( );
cout«"after reading data : "«endl;
[Link]( );
[Link]( );
[Link]( );
return(0);
}
The output would be
count:0
count:0
count:0
After reading data
count: 3
count:3
count:3
The static Variable count is initialized to Zero when the objects created . The count is
incremented whenever the data is read into an object.
Since the data is read into objects three times the variable count is incremented three
times. Because there is only one copy of count shared by all the three object, all the
three output statements cause the value 3 to be displayed.
STATIC MEMBER FUNCTIONS:-
A member function that is declared static has following properties :-
1. A static function can have access to only other static members declared in
the same class.
2. Static member function accepts static data member only.
3. A static member function can be called using the class name as follows:-
class - name :: function - name;
Example:-
#include<iostream.h>
class test
{
int code;
static int count; // static member variable
public:
void set(void)
{
code=++count;
}
void showcode(void)
{
cout<<”object member : “<<code<<end;
}
static void showcount(void)
{
cout<<”count=”<<count<<endl;
}
};
int test:: count;
int main()
{
test t1,t2;
[Link]( );
[Link]( );
test :: showcount ( ); '
test t3;
[Link]( );
test:: showcount( );
[Link]( ) ;
[Link]( );
[Link]( );
return(0);
}
output:- count : 2
count: 3
object number 1
object number 2
object number 3
FRIEND FUNCTIONS:-
Definition: “Friend function is a normal C++ function that can access
private members of the class to whom it is declared as friend .”
We know private members cannot be accessed from outside the class. That is a non
- member function can't have an access to the private data of a class. However
there could be a case where two classes manager and scientist, have been defined we
should like to use a function income-tax to operate on the objects of both these
classes.
In such situations, c++ allows the common function lo be made friendly with both
the classes , there by following the function to have access to the private data of
these classes . Such a function need not be a member of any of these classes.
To make an outside function "friendly" to a class, we have to simply declare this
function as a friend of the classes as shown below :
class ABC
{
---------
---------
public:
--------
----------
friend void xyz(void);
};
The function declaration should be preceded by the keyword friend.
The function is defined elsewhere in the program like a normal C ++ function.
The function definition does not use their the keyword friend or the scope operator ::
The functions that are declared with the keyword friend are known as friend
functions.
A function can be declared as a friend in any no of classes. A friend function, as though
not a member function, has full access rights to the private members of the class.
Friend function special characteristics:
1. It is not in the scope of the class to which it is declared as friend.
2. Since it is not in the scope of the class it cannot be called using an object of the
class.
3. It can be invoked like a normal c++ function without the help of any object.
4. Unlike member function, it cannot access the data members directly and has to
use an object name and dot (.) operator.
5. It can be declared either in the public or private sections of a class without
affection its meaning.
Example:
#include<iostream.h>
class sample
{
int a;
int b;
public:
void setvalue( )
{
a=25;
b=40;
}
friend float mean( sample s);
}
float mean (sample s)
{
return (float(s.a+s.b)/2.0);
}
int main ( )
{
sample x;
x . setvalue( );
cout<<”mean value=”<<mean(x)<<endl;
return(0);
}
A function friendly to two classes:
#include<iostream.h>
class abc;
class xyz
{
int x;
public:
void setvalue(int i)
{
x=i;
}
friend void max (xyz, abc);
};
class abc
{
int a;
public:
void setvalue( int i)
{
a=i;
}
friend void max(xyz,abc);
};
void max( xyz m, abc n)
{
if(m . x >= n.a)
cout<<m.x;
else
cout<< n.a;
}
int main( )
{
abc j;
j . setvalue( 10);
xyz s;
[Link](20);
max( s , j );
return(0);
}
ARRAY OF OBJECTS:-
#include<iostream.h>
#include<conio.h>
class emp
{
private:
char name[20];
int age, sal;
public:
void getdata( );
void putdata( );
};
void emp : : getdata( )
{
coul<<”enter empname”: .
cin>>name;
cout<<”enter age:”<<endl;
cin>>age;
cout<<”enter salun :”;
cin>>sal;
}
void emp :: putdata ()
{
cout<<”emp name:”<<name<<endl;
cout<<”emp age:”<<age<<endl;
cout<<”emp salary:”<<sal;
}
void main()
{
emp foreman[5];
for(int i=0;i<5;i ++)
{
cout<<” for foreman:”;
foreman[i] . getdata();
}
cout<<endl;
for(i=0;i<5;i++)
{
foreman[i].putdata(); .
}
getch();
return(0);
}
Object as a function arguments
Object can be used as function arguments. The object can be passed to the function by
two ways:
1. Pass by values: A copy of entire object is passed to the function .
2. Pass – by –reference : Only the address of the object is passed to the function
As in first case, a copy of entire object is passed to the function. The function creates
another copy of that object and therefore any changes made to the object inside the
function do not affect the actual object. This method is also called Pass-by-value
The second method is called Pass-by-reference. In this method, the address of the
object is passed to the function. Any changes made to the object inside the functions
are directly reflected to the actual object.
Advantage of Pass-By- Reference:
o The pass-by-reference method is more efficient than pass-by value since it
requires passing only the address of the object and not the entire copy. Thus
it saves memory space.
o Any changes made in the functions are reflected to the actual object
Example:
#include<iostream>
class time
{
int hr , min;
public :
void setdata (int , int);
void add (time ,time );
void showdata (void);
};
void time :: setdata (int hh , int mm)
{
hr = hh;
min =mm;
}
void time :: add (time t1 , time t2)
{
hr = [Link] + [Link];
min = [Link] + [Link];
if ( min >= 60 )
{
hr = hr + (min / 60);
min = min % 60;
}
}
void time :: showdata(void)
{
std::cout<< hr<< ":" << min ;
}
int main()
{
time t1,t2,t3;
[Link] (3,50);
[Link] (4 ,30);
[Link] (t1, t2); // result is in t3
[Link]();
}
Returning entire object from the function
Example:
class complex
{
int real,;
float img;
public :
void setdata ( int , float);
complex add (complex);
void showdata(void);
};
void complex :: setdata ( int r, float I)
{
real = r;
img =I;
}
complex complex :: add ( complex c2)
{
complex temp; // create a temporary object
temp. real = real + [Link] ;
temp. img = img + [Link]; // result is in temp object
return temp; // return temp object to the main prog.
}
void complex :: showdata (void)
{
cout << real << “+” << “i” << img;
}
void main(void)
{
complex c1,c2,c3;
[Link](5,-6)
[Link] ( 3,4);
c3 = [Link] (c2); // c2 is explicitly passed, result will be in c3.
[Link]();
}
CONSTRUCTOR:
Definition: “A constructor is a special member function that is executed
automatically whenever the object of a class is created.”
It is special because its name is the same as the class name. The constructor is invoked
whenever an object of its associated class is created. It is called constructor because
it construct the values of data members of the class.
The main task of the constructor is to initialize data members of the object when it is
created.
It is always good ,if we can initialize data members of an object without making a call
to a member function
Syntax:
class employee
{
int a, b;
float salary;
public :
employee (void ) ; // declaration of constructor
};
employee :: employee (void ) // definition of constructor
{
a =0 ;
b= 0;
}
Or
class employee
{
int a, b;
float salary;
public :
employee (void )
{
a=0;
b=0;
}
};
No need to write any statement to invoke the constructor function as we do with the
normal member function.
If normal function is defined for initialization we would need to be invoke this
function for each of the objects separately.
This would be very inconvenient in case of large number of objects
When a class with constructor is defined, the constructor is automatically invoked
when object is created.
employee e1; // constructor is invoked.
The above statement creates the object e1 of type employee and at the same time its
data members are initialized with given values in constructor.
CHARACTERICTICS OF CONSTRUCTOR:
Constructor has the same name that of the class
Constructor is invoked automatically when the object of the class is created.
Constructor must be declared / defined in the public section of a class.
They do not have return data type.
Constructors can not be inherited, but a derived class can call the constructor of the
base class.
Constructors can have default values.
Constructors can take parameters.
Constructor can be virtual.
One cannot refer the address of constructor.
Constructor makes implicit call to the operators new and delete when memory
allocation is required.
Types of Constructors:
Default constructors
Parameterized constructor
Copy constructors
Constructors with Default arguments
Overloaded Constructor
Default constructors:
A constructor that accept no parameter is called the default
constructor.
If no such constructor is defined, then the compiler supplies a default constructor
Therefore a statement such as :-
employee e ;
//invokes the default constructor of the compiler of the compiler to
//create the object "a" ;
Example:
class employee
{
int a , b;
public :
employee() // default constructor
{
a=0;
b =0 ;
}
};
void main()
{
employee e;
}
Parametrized constructors:
It may be necessary to initialize the various data elements of different objects with
different values when they are created.
This objective can be achieved by passing parameters (arguments) to the constructor
when the object is created.
“The constructors can take arguments are called parameterized
constructors”.
Example:
class employee
{
int a , b;
public :
employee ( int ,int); // constructor declaration
};
employee :: employee ( int aa , int bb) // parameterized constructor
{
a =aa ;
b = bb;
}
When a constructor has been parameterized the object declaration such as
employee e1 // may not work.
This is because we have to pass initial values as arguments to the constructor when
object is declared.
Passing the initial values to the constructor can be done in two ways
o By calling the constructor implicitly.
employee e1 ( 10,30 ) ; // implicit call
o By calling the constructor explicitly.
employee e1 = employee ( 10 ,30 ); // explicit call
Both the statements creates object e1 and initialize data members a to 10 and b to 30.
#include<iostream.h>
class integer
{
int m, n;
public:
integer (int, int); // constructor declared
void display (void)
{
cout << "\n m=" << m ;
cout << "\n n=" << n ;
}
};
integer :: integer (int x, int y) // constructor defined
{
m = x; n = y ;
}
int main()
{
integer int1 (0, 100) ;// IMPLICIT call
integer int2 = integer (25, 75); // EXPLICIT call
[Link]();
[Link]();
return 0;
}
COPY CONSTRUCTOR:
A copy constructor is used to declare and at the same time initialize
an object from another object.
For example,
Complex c2 (c1); // copy constructor invoked
OR
Complex c2 =c1; // copy constructor invoked
In both the cases copy constructor will be invoked.
Both the statements would define object c2 and at the same time initialize it to the
value of c1.
Copy constructor copies data member –by-member from one object to another.
In the above case data would be copied member –by-member from c1 to c2.
A copy constructor takes a reference to an object of the same class.
Example:
#include<iostream.h>
class code
{
int id;
public:
code ( )
{
} // default constructor
code (int a)
{
id =a;
}
code ( code &x) // copy constructor takes object of the same class by reference
{
id = [Link];
}
void display()
{
cout <<" \n ID = " <<id ;
}
};
void main()
{
code c1(3);
code c2 (c1); // copy constructor is invoked
code c3 = c1; // copy constructor is invoked
[Link]();
[Link]();
[Link]();
}
Multiple Constructor or Overloaded Constructor:
A class can have more than one constructor. In other words constructors can be
overloaded.
When overloaded, compiler selects an appropriate version of constructor depending
upon the number and type of arguments passed to it.
By using this concept in program user can create different object with various
methods & initialization.
The following example shows how constructors can be overloaded.
class employee
{
int a , b;
public:
employee ( ) // (1) default constructor
{
a =0 ; b =0;
}
employee ( int x ) // (2) constructor with one arguments
{
a =x ;
b = x;
}
employee ( int x ,int y ) // (2) constructor with two arguments
{
a =x;
b =y;
}
};
The above class has three constructors.
o The first constructor receives no arguments
o The second constructor receives one integer
o The third constructor receives two integers.
While executing the constructor, compiler matches number and types of arguments
passed to it and accordingly it executes respective constructor.
For example for statements
employee e1;
//It would invoke the first constructor and set both a’s and b’s values of e1 to 0.
employee e2(10);
//It would invoke the second constructor and set both a’s and b’s values of e2 to 10
employee e3 ( 10,20);
// It would invoke the third constructor and set a’s value to 10 and b’s values to 20.
Constructor with default argument
It is possible to define a constructor with default arguments.
We can assigned default values for one or more parameters at the
time of function declaration, which is used when those corresponding
parameters are omitted in the call to the constructor.
For example the constructor complex ( ) can be declared as follows:
Complex ( float real, float image=0);
Here the image argument has the default value 0.
Then the statement : Complex (5.0), assigns value 5.0 to the real variable and 0.0 to
the image (by default).
However the statement Complex(5.0, 4.5) will assign 5.0 to the real and 4.5 to the
image variables.
The actual parameters when specified override the default value.
Example:
#include<iostream.h>
class Complex
{
private:
float real , image;
public:
Complex( float r, float i=0.0)
{
real = r;
image = i ;
}
void show()
{
cout << "\n Real :" <<real;
cout << "\n Imaginary :" << image;
}
};
int main()
{
Complex c1(2.3);
Complex c2(2.3,3.4);
[Link]();
[Link]();
}
Destructor
Used to destroy the objects that have been created by a constructor
Like constructor, the destructor is a member function whose name is the same as the
class name but is preceded by ~ symbol.
Example:
~student()
{
--
--
}
It never takes any argument
It does not return any value
It will be invoked implicitly by the compiler upon exit from the program to clean up
the storage that is no longer accessible
delete keyword is used to free the memory
Example:
#include <iostream.h>
int count=0;
class alpha
{
public:
alpha()
{
count++;
cout<<"\n No of object created: "<<count;
}
~alpha()
{
count--;
cout<<"\n No of object destroyed: "<<count;
}
};
int main()
{
cout<<"\n entering Main...";
alpha a1,a2,a3,a4;
{
cout<<"\n entering Block 1...";
alpha a5;
}
{
cout<<"\n entering Block 2...";
alpha a6;
}
cout<<"\n Re-entering Main...";
return 0;
};
Difference between Constructor and Destructor
Constructor Destructor
A constructor is a special member function A destructor is a special member function
whose task is to initialize the objects of its class. whose task is to destroy the objects that have
been created by constructor.
It constructs the values of data members of the It does not construct the values for the data
class. members of the class.
It is invoked automatically when the objects It is invoked implicitly by the compiler upon
are created. exit of a program/block/function.
Constructors are classified in various types Destructors are not classified in any types.
such as :
Default constructor
Parameterized constructor
Copy constructor
Overloaded constructor
A class can have more than one constructor. A class can have at the most one constructor.
Constructor accepts parameters. Also it can Destructor never accepts any parameter.
have default value for its parameter.
Syntax: Syntax:
classname() destructor name is preceded
{… with tilde.
… ~classname()
} {….
….
}
Example: Example:
ABC() ~ABC()
{ {
… ….
} }
References:
1. Object Oriented Programming with C++ Book by E Balaguruswamy
2. Model Answer Papers by MSBTE