Constuctor and Destructor
Constructor is a special type of function which has the same name as the class name. Constructor is being automatically call at the time of object declaration and it has no return type.
There are three types of constructor.
- Default Constructor
- Parameterized Constructor
- Copy Constructor
Default Constructor
The constructor with no parameter is called default constructor.
Example:
#include< iostream.h >
class rect
{
public: //access specifier
int height; // data member
int width;
int area;
rect() // default constructor
{
height=20;
width=30;
area=height*width;
cout<< "Area of rectangle ="<< area;
}
};
void main()
{
rect rect1; // createing object
}
Output:
Parameterized Constructor
The constructor with parameter is called default constructor.
Example:
#include< iostream.h >
class rect
{
public: //access specifier
int area;// data member
rect(int height,int width) // default constructor
{
area=height*width;
cout<< "Area of rectangle ="<< area;
}
};
void main()
{
rect rect1(20,30);
}
Output:
Copy Constructor
A constructor that is used to copy or initilize the value of one object into another object.
In this type of constructor one object with parameter is copied into another object so it is called constructor.
Example:
#include< iostream.h >
class rect
{
public: //access specifier
int area;// data member
rect(int height,int width) // default constructor
{
area=height*width;
}
void show()
{
cout<< "Area of rectangle ="<< area;
}
};
void main()
{
rect rect1(20,30);
rect1.show(); // calling function
rect rect2=rect1; // copying object rect1 into rect2
rect2.show(); // calling function
}
Output:
Area of rectangle = 600
Area of rectangle = 600
Destructor
Destructor is a special member function that is executed automatically. When an object is created by constructor destructor destroy the object of the constructor.
Destructor are used to de- allocate the memory that has been allocated for the object by constructor. A destructor declaration should always begain with the tilde (~) symbol. its name is same as class name.
#include< iostream.h >
class demo
{
public: // access specifier
demo() // constructor
{
cout<< "I am inside constructor" <<"\n";
}
~demo() // destructor
{
cout<< "I am inside destructor" <<"\n";
}
};
void main()
{
demo obj;
}
Output:
I am inside constructor
I am inside destructor