A constructor (having the same name as that of the class) is a member function which is automatically used to initialize the objects of the class type with legal initial values.

Destructors are the functions that are complimentary to constructors. These are used to deinitialize objects when they are destroyed. A destructor is called when an object of the class goes out of scope, or when the memory space used by it is de allocated with the help of delete operator.

It is defined like other member functions of the class, i.e., either inside the class definition or outside the class definition

For example, the following program illustrates the concept of a constructor

To demonstrate a constructor

 #include <iostream>
 Class rectangle
 private :
 float length, breadth;
 rectangle ()//constructor definition
 //displayed whenever an object is created
 cout<<”I am in the constructor”;
 float area()
 return (length*breadth);
 void main()
 rectangle rect; //object declared
 cout<<”\nThe area of the rectangle with default parameters
Share with : Share on Linkedin Share on Twitter Share on WhatsApp Share on Facebook