Constructor is a member function and its name is as like as class name. It is used to initialize the class object. Constructor & Destructor both are necessary for every class. If we don’t create them compiler automatically create them by himself. Constructor & Destructor has no return type. It is called when a class object is created. Constructor & Destructor has no statement primarily. But we can create custom statement. Constructor may have parameter or not.
//Body of Constructor
Types of Constructor
There are three types of constructor
- Default Constructor – It does not take any parameter.
- Parameterized Constructor – It accept parameters.
- Copy Constructor – A Special type of constructor which takes an object as argument. It is used to copy values of data member of one object into other object.
Destructor is used to delete object instance from the memory. We need to destroy object instance after its task. If we don’t does this compiler automatically do this? Its name is as like class name. Only extra ~ sign is used before its name. It has no parameter and it doesn’t accept any operator.
The following limitations apply to constructors and destructors:
- Constructors and destructors do not have return types nor can they return values.
- References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.
- Constructors cannot be declared with the keyword virtual.
- Constructors and destructors cannot be declared static, const, or volatile.
- Unions cannot contain class objects that have constructors or destructors.
Difference between Constructor and Destructor
|It is used to initialize the instance of a class.||It is used to destroy the instance of a class.|
|It is called when new instance of a class is created.||It called when instance of a class is deleted.|
|It allocates the memory.||It releases the memory.|
|It may have parameter or not.||It has no parameter.|
|Overloading is possible||Overloading is not possible.|
|Its name is as like class name.||Its name is as like class name but with (~) tiled operator.|