Unit II
Unit II
3 Variables are created on the stack memory Objects are created on the heap memory
4 Only variables are declared Both variables and functions are declared
5 Structures don’t have constructor and destructor Classes have constructor and destructor
6 Data is not hidden (like private or protected) Can be hidden outside the class (like private or
protected)
7 The member variables can not be initialized The member variables can be initialized directly.
directly
2.1] Class & Object: Introduction, Specifying a class, access specifies, defining
member functions, creating objects, memory allocation for objects
Specifying a Class:-
Definition:- A class is a way to bind the data and its associated member functions together.
A class specification has two parts:
l. Class declaration:-
2. Class function definitions:-
The general form of a class declaration is:
▪ The ‘class’ is the keyword which follows the class_name.
▪ The body of a class is enclosed within braces and terminated by a semicolon.
▪ The class body contains the declaration of variables and functions. The variables are known as data members
and functions are known as member functions. They are grouped under two sections, namely, private and
public.
▪ The use of the keyword private is optional. By default, the members of a class are private.
▪ The data members are kept private
and member functions are kept public.
▪ Private members can have access only
within the class and public members can
have access outside the class.
▪ This is illustrated in fig.
Fig: Data hiding in classes
A Simple Class Example:-
#include<iostream.h>
#include<conio.h>
class Item
{
private:
int number; //variables declaration private by default
float cost;
public:
void getdata(int a, float b);//function declaration using prototype
void showdata(void);
}; //end with semicolon
int main(void)
{
clrscr();
Item t1;
t1.getdata(2,45.78);
t1.showdata();
getch();
return 0;
}
void Item::showdata(void)
{
cout << “Number :” <<number << “\n“;
cout << “cost :” <<cost << “\n”;
}
Since these functions do not return any value, their return type is void.
2. Inside the Class Definition:-
Function is defined inside the class as follows:
#include<iostream.h>
#include<conio.h>
class Item {
private:
int number; //variables declaration private by default
float cost;
public:
void getdata(int a, float b)
{
number=a;
cost=b;
}
void showdata(void) //definition inside the class
{
cout<<"Number :"<<number<<"\t"<<"Cost :"<<cost;
}
};
int main(void)
{
clrscr();
Item t1;
t1.getdata(2,45.78);
t1.showdata();
getch();
return 0;
}
Inline functions:-
Inlining is only request to the compiler and not a command. Compiler can ignore the request for inlining.
Compiler may not perform inlining in such circumstances like:
1. If a function contains a loop e.g. for , while ,do-while
2. If a function contains static variables.
3. If a function is recursive.
4. If a function return type is other than void and the return statement doesn’t exist in a function body.
5. If a function contains switch or goto statement.
Advantages:-
1. Function call overhead doesn’t occur.
2. It also saves the overhead of push/pop variables on the stack when function is called.
public:
void getdata(int a, float b);//function declaration using prototype
void showdata(void);
}; //end with semicolon
inline void Item::getdata(int x, float y)
{
number=x;
cost=y;
}
inline void Item::showdata()
{
cout<<"Number :"<<number<<"\t"<<"cost :"<<cost;
}
int main()
{
clrscr();
Item t1;
t1.getdata(2,45.78);
t1.showdata();
getch();
return 0;
}
Nesting of member function:-
A member function can be called by using its name inside another member function of the same class.
This is known as nesting of member functions.
class set
{
int m,n;
public:
void input(void);
void display(void);
int largest(void);
};
int set :: largest( void)
{
if(m >= n)
return (m);
else return(n); }
void set ::input(void)
{
cout <<"Input values of m and n" << "\n";
cin>>m>>n;
}
return 0;
}
Memory allocation for objects:-
▪ Memory space for objects is allocated when they are declared and not when the class is specified. This
statement is only partly true.
▪ Actually, the member functions are created and placed in the memory space only once when they are
defined as a part of a class specification.
▪ Since all the objects belonging to that class use the same member functions, no separate space is allocated
for member functions when the objects are created.
▪ Only space for member variables is allocated separately for each object.
▪ Separate memory locations for the objects are essential, because the member variables will hold different
data values for different objects. This is shown in below fig.
2.2] Static data member, Static member Function, friend Function
Static data member:-
A static member variable has certain special characteristics as below:
• It is initialized to zero when the first object of its class is created. No other initialization is permitted.
• 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.
• It is visible only within the class, but its lifetime is the entire program. Sample program is as below:
#include<iostream.h>
#include<conio.h>
class Counter
{
static int count;
int number;
public:
void getdata(int a)
{
number =a; count++;
}
void getCount()
{
cout<<"the value of counter :"<<count<<endl;
}
};
int main()
{
Counter c1,c2,c3;
clrscr();
c1.getCount();
c2.getCount();
c3.getCount();
c1.getdata(100);
c2.getdata(200);
c3.getdata(300);
▪ Static variables are like non-inline member functions as they are declared in a class declaration and
defined in the source file.
▪ While defining a static variable, some initial value can also be assigned to the variable. For instance, the
following definition gives count. the initial value 10.
int Counter::count=10;
The static function showCount() displays the number of objects created till that moment. A count of
number of objects created is maintained by the static variable count. The function showCode() displays the code
number of each object.
#include<iostream.h>
#include<conio.h>
class Test
{
int code;
static int count;
public:
void setCode(void)
{code= ++count;}
void showCode(void)
{cout<<"oject number :"<<code<<endl;}
int Test::count;
int main()
{ clrscr();
Test t1, t2;
t1.setCode();
t2.setCode();
Test::showCount();
Test t3;
t3.setCode();
Test::showCount();
t1.showCode();
t2.showCode();
t3.showCode();
getch();
return 0;
}
The statement
code =++count;
is executed whenever setCode( ) function is invoked and the current value of count is assigned to code. Since
each object has its own copy of code, The value contained in code represents a unique number of its object.
Friend Function:
A non member function cannot have access to the private data of a class. But there could be a situation
where we would like two classes to share a particular function.
▪ In some situations, C++ allows the common function to be made friendly with both the classes, thereby
allowing 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 class
as shown below:
A friend function possesses certain special characteristics:
▪ It is not in the scope of the class to which it has boon declared as friend.
▪ Since it is not in the scope of the class, it cannot be called using the object of that class.
▪ It can be invoked like a normal function without the help of any object.
▪ Unlike member functions, it cannot access the member names directly and has to use an object name and dot
membership operator with each member name.(e.g. A.x).
▪ It can be declared either in the public or the private part of a class without affecting its meaning.
▪ Usually, it has the objects as arguments.
#include<iostream.h>
#include<conio.h>
class Sample
{
int a,b;
public:
void setvalue(){a=20;b=40;}
float getMean(Sample s)
{
return (s.a+s.b)/2;
}
int main(void)
{
clrscr();
Sample x;
x.setvalue();
Output:
XYZ xyz;
xyz.setValue(30);
maxValue(xyz,abc);
getch();
return 0;
}
Output:
Output:-
Values before exchange
The value of value1 is:200
The value of value2 is:100
Output:-
Details of manager :1
Name: Amit
Age:23
Details of manager :2
Name: Pankaj
Age:34
Details of manager :3
Name: Amruta
Age:33 Fig: Storage of data items of an object array
Object as function argument:-
An object may be used as a function argument in two ways:
▪ A copy of the entire object is passed to the function.
▪ Only the address of the object is transferred to the function.
▪ The first method is called pass by value i.e. Since a copy of the object is passed to the function, any
changes made to the object inside the function do not affect the object used to call the function.
▪ The second method is called pass by reference. When an address of the object is passed, the called
function works directly on the actual object used in the call. This means that any changes made to the
object inside the function will reflect in the actual object.
▪ The pass by reference method is more efficient since it requires to pass only the address of the object and
not the entire object.
Below program illustrates the use of objects as function arguments. It performs the addition of time in the
hour and minutes format:
#include<iostream.h>
#include<conio.h>
class Time
{
int hours, minutes;
public:
void getTime(int h, int m){hours=h; minutes=m;}
void showTime(void)
{
cout<<"Hours : "<<hours<<"\t";
cout<<"Minutes : "<<minutes<<endl;
}
#include<iostream.h>
#include<conio.h>
class Integer
{
int m,n;
public:
Integer(int , int);
void display(void)
{
cout<<"M= :"<<m;
cout<<"N= :"<<n<<endl;
}
};
Integer::Integer(int x, int y)
{
m=x;n=y;
}
int main(void)
{
clrscr();
Integer int1(0,100);
Integer int2=Integer(25,25);
cout<<"Object 1 :";int1.display();
cout<<"Object 2 :";int2.display();
getch();
return 0;
}
Default Constructor:-
• It is possible to define constructors with default arguments. For example, the constructor complex() can be
declared as follows:
int main()
{ clrscr();
Complex A(3.5,4.7);
Complex B(1.2);
Complex C;
C=sum(A,B);
cout<<"A=";show(A);
cout<<"B=";show(B);
cout<<"C=";show(C);
getch();
return 0;
}
2.6] Destructors:-
▪ A destructor is used to destroy the objects that have been created by a constructor.
▪ The destructor is a member function whose name is the same as class but is preceded by a tilde sign(~).
▪ A destructor never takes any argument and does not it return any value.
▪ It will be invoked implicitly by the compiler on exit from the program to clean up storage (objects)that is no
longer in use.
▪ It releases memory space for future use.
e.g. the destructor for the class Employee can be defined as shown below:
~Employee()
{
}
#include<iostream.h>
#include<conio.h>
int count=0;
class Alpha
{
public:
Alpha()
{
count++;
cout<<"Number of objects created :"<<count<<endl;
}
~Alpha()
{
cout<<"Number of objects destroyed :"<<count<<endl;
count--;
}
};
int main(void)
{
clrscr();
{
cout<<"ENTER BLOCK 2 :"<<endl;
Alpha a4;
}