C++ Chapter3
C++ Chapter3
]
Class and Objects
A class is a way to bind the data and its associated functions together. It allows the data (and functions)
to be hidden, if necessary, from external use. When defining a class, we are creating a new abstract data
type that can be treated like any other built-in data type.
Objects are the basic run-time entities in an object-oriented system. They may represent a person, a
place, a bank a bank account, a table of data or any item that the program has to handle.
Example
#include<iostream>
using namespace std;
class addition
{
private:
int a, b, sum;
public:
void getdata();
void processing();
void display();
};
void addition::getdata()
{
cout<<"\n Enter two numbers";
cin>>a>>b;
}
void addition::display()
{
cout<<"\n Sum of two numbers is ="<<sum;
}
int main()
{
1
addition a;
a.getdata();
a.processing();
a.display();
return 0;
}
Nesting of member functions:
We know that a member function of a class can be called only by an object of that class using a
dot operator. However, there is an exception to this. 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 function.
Example:
#include<iostream>
using namespace std;
class set
{
int m,n;
public:
void input(void);
void display(void);
int largest(void);
};
int main()
{
2
set A;
A.input();
A.display();
return 0;
}
Constructor
A constructor is a special member function whose task is to initialize the object of its class . It is
special because it name is same as that of class name. Constructor is invoked whenever the
object of its associated class is created. It is called constructor because it constructs the values of
data members of the class . It has no return type, not even void but can take arguments.
Examples:
class sample
{
int a, b;
public:
Sample () // constructor
{
a = 0; b=0;
}
};
int main ()
{
Sample s1; // object s1 created
…………
………..
}
Above object declaration not only creates the object s1, but also initializes its data member’s ‘a’
and ‘b’ to zero.
Some characteristics of constructor
1. They should always be declared in public section.
2. They are invoked automatically when the object are created.
3. They don’t have return types, not even void so they can’t return values.
4. They can’t be inherited, though a derived class can call the base class constructor.
5. Like other C++ function, they can have default arguments.
3
Default Constructor
Example
#include <iostream>
using namespace std;
class Demo
{
int p,g;
public:
Demo () // constructor declared / defined
{
p = 0;
g = 0;
}
void display ()
{
cout <<p<<g;
}
};
int main ()
{
Demo d;
d.display ();
}
Parameterized Constructor
Sometime, it may be necessary to initialize the various data elements of different objects with
different values when they are created. Constructors that take arguments as parameters are
called parameterized constructor.
Example:
class integer
{
int m, n;
public:
integer (int x, int y); // parameterized constructor
};
integer:: integer (int x,int y)
4
{
m = x;
n = y;
}
When a constructor has been parameterized. The object declaration statement such as:
Integer int1; may not work.
Now, we must pass the initial values as arguments to the constructor function, when an
object is declared. This can be done in 2 ways:-
1. By calling the constructor explicitly
2. By calling the constructor implicitly
Example:
integer int1 = integer (0, 100); // explicit call
This statement creates an integer object int1 and passes the values 0 and 100
Eg: integer int1 (0, 100); // implicit call
This method is sometimes called shorthand method and is used very often as it is shorter,
looks better and is easy to implement.
Eg:
#include <iostream>
using namespace std;
class param
{
int a, b;
public:
param (int, int);
void display ()
{
cout <<a<<" "<<b<<endl;
}
};
param:: param (int x, int y)
{
a = x;
b = y;
}
int main()
{
param p1 = param (10, 20); // expilit call
param p2(50,60);//implicit call
p1.display();
p2.display();
}
Notes:
5
The parameter of a constructor can be of any type except that of the class to which it belongs
Eg.
class B
{
…………
B(B); // it is illegal
………..
};
However, a constructor can accept reference to its own class as parameters.
Eg:
class B
{
B(&B); // it is legal
……….
………
};
Copy Constructor
It is used to declare and initialized an object from another object i.e it is used to copy data
members of an object of a class into another object of the same class .
For eg:
sample (sample & s); // copy constructor
Eg:
sample s2(s1);
Would define the object s2 and at the same time initialize it to the value of s1.
Another form:
Sample s2 = s1;
The process of initializing through a copy constructor is known as copy initialization.
Note:
S2 = S1;
Will not invoke the copy constructor but, if S1 and S2 are objects, then this statement is legal
and assigns the value of S1 and S2. This is the task of overloaded assignment operator (=).
A copy constructors takes a reference to an object of the same class as itself as an argument.
Example of copy constructor
#include<iostream>
using namespace std;
class Copy
{
int id;
6
public:
Copy() { }// constructor
Copy(int x) //constructor
{
id = x;
}
Copy(Copy & y) //copy constructor
{
id = y.id;
}
void display()
{ cout<<id; }
};
int main()
{
Copy A (20); // object A is created & initialized
Copy B(A); // copy constructor called
Copy C = A; // copy constructor called again
Copy D; // D is created, not initialized
D = A; // copy constructor not called
Notes:
A reference variable has been used as an argument to the copy constructor. We cannot pass
the argument by value to a copy constructor.
When no copy constructor is defined, the compiler supplies its own copy constructor. If we
don’t define our own copy constructor, the C++ compiler creates a default copy constructor
for each class which does a member-wise copy between objects. The compiler created copy
constructor works fine in general. (NOTE: Students are advised to check above program
without using copy constructor definition)
7
Multiple constructors in a class
integer (); // no arguments.
Integer (int, int); // two arguments
C++ allows both these constructors in the same class :
class integer
{
int x,y;
public:
integer () // constructor 1
{ x=0; y=0; }
};
8
{
float x,y;
public:
complex(){}
complex(float a){x=y=a; }
complex(float real, float imag)
{x= real; y= imag;}
void sum(complex,complex);
void show();
};
void complex::sum (complex c1, complex c2)
{
x = c1.x + c2.x;
y= c1.y + c2.y;
void complex::show()
{
cout<<x<<"+j"<<y<<"\n";
}
int main()
{
complex A(2.7,3.5);
complex B(1.6);
complex C;
C.sum(A,B);
cout<<"A="; A.show();
cout<<"B=";B.show();
cout<<"C=";C.show();
return 0;
}
9
complex() { }
complex(float a)
{ x=y = a; }
10
Example:
#include <iostream>
using namespace std;
int count = 0;
class destruct
{
public:
destruct ()
{
count++;
cout <<"\n no. of object created is" << count;
}
~destruct ()
{
cout <<"\n no. of object destroyed" <<count;
count --;
}
};
int main()
{
destruct d1, d2, d3;
return 0;
}
O/P
No. of object created : 1
No. of object created : 2
No. of object created : 3
Example:
# include <iostream>
using namespace std;
int count=0;
class alpha
{
public:
alpha()
{
11
count++;
cout<<"\n no. of object created"<<count;
}
~alpha()
{
cout<<"\n no. of object destroyed"<<count;
count--;
}
};
int main ()
{ cout <<"\nenter main";
{ alpha A1, A2, A3, A4;
{ cout<<"\n enter block1";
alpha A5;
}
{
cout<<"\n enter block2";
alpha A6;
}
cout<<"\n RE-ENTER MAIN";
}
return 0;
}
O/P
Enter Main
No. of object created 1
No. of object created 2
No. of object created 3
No. of object created 4
Enter Block 1
No. of object created 5
No. of object destroyed 5
Enter Block 2
No. of object created 5
No. of object destroyed 5
RE-ENTER MAIN
No of object destroyed 4
No of object destroyed 3
No of object destroyed 2
12
No of object destroyed 1
Note:
The constructor can also be used to allocate memory while creating objects. This will enable the
system to allocate the right amount of memory for each object when the objects are not of the
same size, thus resulting in the saving of memory. Allocation of memory to objects at the time of
their construction is known as dynamic construction of object. The memory is allocated with the
help of “new” operator.
Like any other data type, an object may be used as a function argument. This can be done in two ways.
14
First method is pass-by-value. 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-references. 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.
Example 1
#include<iostream>
using namespace std;
class time
{
int hours;
int minutes;
public:
void gettime(int h, int m)
{
hours=h;
minutes=m;
}
void puttime(void)
{
cout<< hours<<"hours and ";
cout<<minutes<<"minutes"<<endl;
}
15
cout<<"T1=";
T1.puttime( );
cout<<"T2=";
T2.puttime( );
cout<<"T3=";
T3.puttime( );
return(0);
}
Output:
Example 2
#include <iostream>
using namespace std;
class Demo
{
private:
int a;
public:
void set(int x)
{
a = x;
}
void print()
{
cout<<"Value of A : "<<a<<endl;
}
};
int main()
{
16
//object declarations
Demo d1;
Demo d2;
Demo d3;
return 0;
}
Output:
#include <iostream>
using namespace std;
class Example {
public:
int a;
17
int main()
{
Example E1, E2, E3;
E1.a = 50;
E2.a = 100;
E3.a = 0;
return 0;
}
Output
Structures in C
Structure provides method for packing together the data of different types.
Convenient tool for handling a group of logically related data items.
Consider:
struct complex
{
18
int real;
int img;
};
struct complex c1, c2, c3;
The complex number c1, c2, c3 are assigned values using a dot or period operator.
“The 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 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 the 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.
19
Fig: Object of Memory
Static Members
The properties of static member variable are similar to that of a C static variable.
A static member variable has certain special characteristics. These are:
o It is initialized to zero when the first object of its class is created. No other initialization
is permitted.
o 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.
o It is visible only within the class, but its lifetime is the entire program.
o Static variable are normally used to maintain values common to the entire class. For
example, a static data member can be used as a counter that records the occurrences of
all the objects.
Example 1 :
#include<iostream>
using namespace std;
class item{
static int X ;
public:
void get()
{
20
cout<<"X = "<<X<<"\n";
X++;
}
};
a.get();
b.get();
c.get();
return 0;
}
Output:
X=0
X=1
X=2
Example 2
#include<iostream>
using namespace std;
class item
{
static int count; //count is static
int number;
public:
void getdata(int a)
{
number=a;
count++;
}
void get_count(void)
{
cout<<"count:";
cout<<count<<endl;
}
};
21
int item :: count ; //count defined
int main( )
{
item a,b,c;
a.get_count( );
b.get_count( );
c.get_count( );
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout<<"after reading data : "<<endl;
a.get_count( );
b.get_count( );
c.get_count( );
return(0);
}
Output:
Count: 0
Count: 0
Count: 0
after reading data :
Count: 3
Count: 3
Count: 3
The general form of a member function definition outside the class is:
Function body
Example
22
#include<iostream>
#define pi 3.14159
using namespace std;
class addition
{
private:
int a, b, sum;
float r,area;
public:
void getdata();
void display();
void processing();
};
void addition::getdata()
{
cout<<"\n Enter two numbers and radius";
cin>>a>>b>>r;
}
void addition::display()
{
cout<<"\n Sum of two numbers is ="<<sum;
cout<<"\n Arrea of circle is="<<area;
}
void addition::processing()
{
sum=a+b;
area=pi*r*r;
}
int main()
{
addition a;
a.getdata();
a.processing();
a.display();
return 0;
}
23
Output
24