Professional Documents
Culture Documents
Module 3 CPP New
Module 3 CPP New
Module 3 CPP New
Constructors
A constructor is a special member function whose task is to initialize the objects of its class
When a constructor is declared for a class, initialization of the class objects becomes
mandatory.It is special because its name is same as the class name.The constructor is invoked
whenever an object of its associated class is created.It is called constructor because it constructs
the values of data members of the class.It is defined like other member functions of the class,
i.e., either inside the class definition or outside the class definition.
There is no need to write any statement to invoke the constructor function.If a ‘normal’ member
function is defined for zero initialization, we would need to invoke this function for each of the
objects separately.A constructor that accepts no parameters is called the default
constructor.The default constructor for class A is A : : A ( )
Characteristics of Constructors
1. They should be declared in the public section.
2. They are invoked automatically when the objects are created.
3. They do not have return types, not even void and they cannot return values.
4. They cannot be inherited, though a derived class can call the base class constructor.
5. Like other C++ functions, Constructors can have default arguments.
6. Constructors cannot be virtual.
7. We cannot refer to their addresses.
8. An object with a constructor (or destructor) cannot be used as a member of a union.
9. They make ‘implicit calls’ to the operators new and delete when memory allocation is
required.
10. When a constructor is declared for a class initialization of the class objects becomes
mandatory.
Types of constructors
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Dynamic Constructor
Default Constructor
1
2|Page
2
3|Page
{
clrscr();
rectangle rect; //object declared
cout<<”\nThe area of the rectangle with default parameters is:”<<rect.area()<<”sq.units\n”;
getch();
}
Parameterized Constructors
It may be necessary to initialize the various data elements of different objects with different
values when they are created.This is achieved by passing arguments to the constructor function
when the objects are created.The constructors that can take arguments are called
parameterized constructors.
Note:-The parameters can be of any type except that of the class to which it belongs
class add
{
int m, n ;
public :
add (int, int) ;
------
};
add : : add (int x, int y)
{
m = x; n = y;
}
When a constructor is parameterized, we must pass the initial values as arguments to the
constructor function when an object is declared. This can be done in two ways
1. By calling constructor explicitly
add sum = add(2,3); //explicit call
This statement creates an add object sum and passes the values 2 and 3 to it
2. By calling constructor implicitly
add sum(2,3)
This shorthand method is used often as it is easy to implement
Parameterized Constructor-example
#include <iostream.h>
class Crectangle
{
int width, height;
public:
CRectangle (int,int);
int area ()
{
return (width*height);
3
4|Page
}
};
CRectangle::CRectangle (int a, int b)
{
width = a;
height = b;
}
int main ()
{
CRectangle rect (3,4);
CRectangle rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
class add
{
int m, n ;
public :
add ( ) {m = 0 ; n = 0 ;}
add (int a, int b)
{m = a ; n = b ;}
};
The first constructor receives no arguments.
The second constructor receives two integer arguments.
Add a1;
Would automatically invoke the first constructor and set both m and n of a1 to zero.
Add a2(10,20);
Would call the second constructor which will initialize the data members m and n of a2
to 10 and 20 respectively.
Constructor Overloading
More than one constructor functions can be defined in a class. This is called Constructor
Overloading
Multiple Constructors in a Class
class complex
{
float x, y ;
public :
4
5|Page
complex ( ) { }
complex (float a)
{x=y=a;}
complex (float r, float i)
{x=r;y=i}
------
};
complex ( ) { }
This contains the empty body and does not do anything.This is used to create objects without
any initial values.
C + + compiler has an implicit constructor which creates objects, even though it was not
defined in the class.This works well as long as we do not use any other constructor in the class.
However, once we define a constructor, we must also define the “do-nothing” implicit
constructor.
Constructor Overloading
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<string.h> //for strcpy()
class figure
{
private:
float radius, side1,side2,side3; //data members
char shape[10];
public:
figure(float r) //constructor for circle
{
radius=r;
strcpy (shape, “circle”);
}
figure (float s1,float s2) //constructor for rectangle
{
side1=s1;
side2=s2;
side3=radius=0.0; //has no significance in rectangle strcpy(shape,”rectangle”);
}
figure (float s1, floats2, float s3) //constructor for triangle
{
side1=s1;
side2=s2;
side3=s3;
radius=0.0;
strcpy(shape,”triangle”);
}
5
6|Page
Copy Constructor
A copy constructor is used to declare and initialize an object from another object.
integer (integer & i) ;
integer I 2 ( I 1 ) ; or integer I 2 = I 1 ;
The process of initializing through a copy constructor is known as copy initialization.
The statement
I 2 = I 1;
will not invoke the copy constructor.
If I 1 and I 2 are objects, this statement is legal and assigns the values of I 1 to I 2, member-by-
member.
6
7|Page
A reference variable has been used as an argument to the copy constructor.We cannot pass
the argument by value to a copy constructor.
class add
{
int m, n ;
public :
add ( ) {m = 0 ; n = 0 ;}
add (int a, int b)
{m = a ; n = b ;}
add (add & i)
{m = i.m ; n = i.n ;}
};
Add a3(a2);
Would invoke the third constructor which copies the values of a2 into a3.
This type of constructor is called the “copy constructor”.
7
8|Page
}
};
void main()
{
int eno;
float sal;
clrscr();
cout<<”Enter the employee number and salary\n”;
cin>>eno>>sal;
employee obj1(eno,sal);//dynamic initialization of object
cout<<”\nEnter the employee number and salary\n”;
cin>eno>>sal;
employee obj2(eno,sal); //dynamic initialization of object
obj1.display(); //function called
employee obj3=obj2; //copy constructor called
obj3.display();
getch();
}
Dynamic Constructors
The constructors 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. Allocation of memory to objects at the time of their construction is known as dynamic
construction of objects. The memory is created with the help of the new operator.
Destructors
A destructor is used to destroy the objects that have been created by a constructor.
Like constructor, the destructor is a special member function whose name is the same as the
class name but is preceded by a tilde.
eg: ~ integer ( ) { }
A destructor never takes any argument nor does it return any value.
It will be invoked implicitly by the compiler upon exit from the program – or block or
function as the case may be – to clean up storage that is no longer accessible.
It is a good practice to declare destructors in a program since it releases memory space
for further use.
Whenever new is used to allocate memory in the constructor, we should use delete to
free that memory.
It is mainly used to de-allocate dynamic memory locations
Destructors cannot be overloaded
#include <iostream.h>
class CRectangle {
int *width, *height;
8
9|Page
public:
CRectangle (int,int);
~CRectangle ();
int area () {return (*width * *height);}
};
CRectangle::CRectangle (int a, int b) {
width = new int;
height = new int;
*width = a;
*height = b;
}
CRectangle::~CRectangle ()
{
delete width;
delete height;
}
int main ()
{
CRectangle rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
9
10 | P a g e
Overloading in C++
It is one of the many exciting features of C++.C++ has ability to provide the operators with a
special meaning for a data type.The mechanism of giving such special meanings to an operator is
called operator overloading.We can overload (give additional meaning to) all the C++ operators
except:
Class member access operators ( . & .*)
Scope resolution operators ( : : )
Size operator (sizeof)
Conditional operators (? : )
When an operator is overloaded, its original meaning is not lost.
10
11 | P a g e
x op y would be interpreted as
11
12 | P a g e
Type Conversions
In C programming language, when different types of constants and variables are used in expression,
C automatically perform type conversion based on some fixed rules. In assignment operation,
variable at the right hand side is automatically converted to the type of the variable on the left. The
Same can also be possible in C++ programming language.
int a ;
float b = 3.14654;
a = b;
Here ‘b’ is float variable but it is at the right side in the assignment statement so converted into the
integer format.
But this automated type promotion will work well if both data types are of primary data type or both
are of same user-defined data type. But it will create problem when one data type is user-defined
data type and another is primary data type. So for that we have to use some special function for type
conversion as in such cases automatic type conversion can not be performed by the language itself.
12
13 | P a g e
In this type of conversion the source type is basic type and the destination type is class type. Means
basic data type is converted into the class type.
emp = Ecode ;
Here the assignment will be done by converting “Ecode” which is of basic or primary data type into
the class type.
In this type of conversion the source type is class type and the destination type is basic type. Means
class data type is converted into the basic type.
Ecode = emp ;
Here the assignment will be done by converting “emp” object which is of class type into the basic or
primary data type.
In this type of conversion both the type that is source type and the destination type are of class type.
Means the source type is of class type and the destination type is also of the class type. In other
words, one class data type is converted into the another class type.
For example we have two classes one for “computer” and another for “mobile”. Suppose if we wish
to assign “price” of computer to mobile then it can be achieved by the statement below which is the
example of the conversion from one class to another class type.
mob = comp ; // where mob and comp are the objects of mobile and computer classes respectively.
Here the assignment will be done by converting “comp” object which is of class type into
the “mob” which is another class data type.
13
14 | P a g e
As mentioned before, in this type of conversion the source type is basic type and the destination
type is class type. Means basic data type is converted into the class type.
emp = Ecode ;
Here the assignment will be done by converting “Ecode” which is of basic or primary data type
into the class type.
The conversion from basic type to the class type can be performed by two ways:
Using constructor
Using Operator Overloading
Using Constructor
To achieve that we have implemented one constructor function which accepts one argument of
type integer as follow:
#include <iostream.h>
#include <conio.h>
class Time
{
int hrs,min;
public:
Time(int);
void display();
};
Time :: Time(int t)
{
cout<<"Basic Type to ==> Class Type Conversion..."<<endl;
hrs=t/60;
min=t%60;
}
void Time::display()
{
14
15 | P a g e
void main()
{
clrscr();
int duration;
cout<<"Enter time duration in minutes";
cin>>duration;
Time t1=duration;
t1.display();
getch();
}
Here, we have created an object “t1” of class “Time” and during the creation we have assigned
integer variable “duration”. It will pass time duration to the constructor function and assign to
the “hrs” and “min” members of the class “Time”.
We have to note that during type conversion using the constructor we can pass only one
argument and we can do type conversion at the type of initialization only.
/* Program to convert from basic type to class type using operator overloading */
#include <iostream.h>
#include <conio.h>
class Time
{
int hrs,min;
public:
void display();
void operator=(int); // overloading function
};
void Time::display()
{
cout<<hrs<< ": Hour(s) "<<endl ;
cout<<min<<": Minutes"<<endl ;
}
void Time::operator=(int t)
{
15
16 | P a g e
void main()
{
clrscr();
Time t1;
int duration;
cout<<"Enter time duration in minutes";
cin>>duration;
cout<<"object t1 overloaded assignment..."<<endl;
t1=duration;
t1.display();
cout<<"object t1 assignment operator 2nd method..."<<endl;
t1=(duration);
t1.display();
getch();
}
By using overloaded assignment operator we can perform the type conversion at any place in
program.
In this type of conversion the source type is class type and the destination type is basic type. Means class data type
is converted into the basic type.
For example we have class Time and one object of Time class ‘t’ and suppose we want to assign the total time of
object ‘t’ to any integer variable say ‘duration’ then the statement below is the example of the conversion from
class to basic type.
Here the assignment will be done by converting “t” object which is of class type into the basic or primary data type.
It requires special casting operator function for class type to basic type conversion. This is known as the conversion
function. The syntax for the conversion function is as under:
operator typename( )
….
….
….
For example suppose we want to assign time in hours and minutes in the form of total time in minutes into one
integer variable “duration” then we can write the type conversion function as under:
16
17 | P a g e
#include "iostream.h"
#include "conio.h"
#include "iomanip.h"
class Time
int hrs,min;
public:
~Time() // destructor
cout<<"Destructor called..."<<endl;
};
Time::Time(int a,int b)
hrs=a;
min=b;
17
18 | P a g e
return(hrs*60+min);
void main()
clrscr();
int h,m,duration;
cin>>h;
cin>>m;
getch();
duration = t;
We can also specify the casting type and write the same statement by the following way to achieve the
same result.
18
19 | P a g e
It must not specify the return value even though it returns the value.
In this type of conversion both the type that is source type and the destination type are of class type.
Means the source type is of class type and the destination type is also of the class type. In other words,
one class data type is converted into the another class type.
For example we have two classes one for “computer” and another for “mobile”. Suppose if we wish to
assign “price” of computer to mobile then it can be achieved by the statement below which is the example
of the conversion from one class to another class type.
mob = comp ; // where mob and comp are the objects of mobile and computer classes respectively.
Here the assignment will be done by converting “comp” object which is of class type into the “mob” which
is another class data type.
Conversion from one class to another class can be performed either by using the constructor or type
conversion function.
The following program demonstrates conversion from one class to another class type with the help of
conversion function where, we have overloaded “=” operator for conversion purpose.
#include "iostream.h"
#include "conio.h"
#include "iomanip.h"
class inventory1
{
int ino,qty;
float rate;
public:
inventory1(int n,int q,float r)
{
ino=n;
qty=q;
rate=r;
}
inventory1()
{
cout<<"\n Inventory1's Object Created";
}
int getino()
19
20 | P a g e
{
return(ino);
}
float getamt()
{
return(qty*rate);
}
void display()
{
cout<<endl<<"ino = "<<ino<<" qty = "<<qty<<" rate = "<<rate;
}
};
class inventory2
{
int ino;
float amount;
public:
void operator=(inventory1 I)
{
ino=I.getino();
amount=I.getamt();
}
void display()
{
cout<<endl<<"ino = "<<ino<<" amount = "<<amount;
}
};
void main()
{
clrscr();
inventory1 I1(1001,30,75);
inventory2 I2;
I2=I1;
//inventory2 I2=I1;
I1.display();
I2.display();
getch();
}
#include "iostream.h"
#include "conio.h"
#include "iomanip.h"
class Time
{
int hrs,min;
public:
Time(int h,int m)
{
hrs=h;
min=m;
}
20
21 | P a g e
Time()
{
cout<<"\n Time's Object Created";
}
int getMinutes()
{
int tot_min = ( hrs * 60 ) + min ;
return tot_min;
}
void display()
{
cout<<"Hours: "<<hrs<<endl ;
cout<<" Minutes : "<<min <<endl ;
}
};
class Minute
{
int min;
public:
Minute()
{
min = 0;
}
void operator=(Time T)
{
min=T.getMinutes();
}
void display()
{
cout<<"\n Total Minutes : " <<min<<endl;
}
};
void main()
{
clrscr();
Time t1(2,30);
t1.display();
Minute m1;
m1.display();
t1.display();
m1.display();
getch();
}
21