C++ Constructors and Destructors

C++ allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor. This fulfills the requirement for initialization of object upon creation.

Constructors

A constructor initializes an object immediately upon creation.

  • It has the same name as the class in which it resides and is syntactically similar to a function.
  • Once defined, the constructor is automatically called immediately after the object is created.
  • Constructors have no return type, not even void. This is because the implicit return type of a class’ constructor is the class type itself. It is the constructor’s job to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately.

 

Types

1. Default Constructor

A default constructor, also called no-argument constructor, can initialize data members to constant values. 

Syntax:

class_name()
{
     //body
}

For example, if we want to set the dimensions of a box upon creation, then we can use default constructor as,

//default constructor
Box(){
        width = 10;
        height = 10;
        depth = 10;
  }

This constructor gets called upon object creation with arguments as,

Box cube;                  //creating an object cube of type Box; calls default constructor

2. Parameterized Constructor

A parameterized constructor can initialize data members to values passed as arguments.

Syntax:

class_name(params)
{
     //body
}

For example, if we want to set the dimensions of a box upon creation with the values we passed, then we can use parameterized constructor as,

//parameterized constructor
    Box(double w,double h, double d)
    {
        width = w;
        height = h;
        depth = d;
    }

This constructor gets called upon object creation with arguments as,

Box box(2,3,5);            //creating an object cube of type Box; calls parameterized constructor

3. Default Copy Constructor

This constructor is a one argument constructor whose argument is an object of the same class as the constructor.

The following is an example of default copy constructor.

Box box(2,3,5);            //creating an object cube of type Box; calls parameterized constructor 
Box same_box(box);         //this creates same_box object with values same as that of box

 

Constructor Overloading

Constructors can have same name differing in number and types of arugments being passed. All other function overloading rule applies to constructor overloading.

In program below, constructor Box() has two different versions.

 

Destructors

The most common use of destructors is to deallocate memory that was allocated for the object by the constructor.

  • Destructors are called automatically when an object is destroyed.
  • It has the same name as the class in which it resides but is preceded by a tilde and is syntactically similar to a function.
  • Constructors have no return type, not even void. They also take no arguments

Syntax:

~class_name(){
      //body
}

Example:

//destuctor
    ~Box(){
        cout<<"Destructor called."<<endl;
    }

 

Here is example program that uses all 3 types of constructors and destructor mentioned above.

//example of constructors

#include<iostream>
using namespace std;

//declaring a class
class Box
{
private:
    //data members
    double width;
    double height;
    double depth;
    float volume;
public:
    //default constructor
    Box()
    {
        width = 10;
        height = 10;
        depth = 10;
    }
    //parameterized constructor
    Box(double w,double h, double d)
    {
        width = w;
        height = h;
        depth = d;
    }
    //member functions
    void calculateVolume()
    {
        volume = width * height * depth;
    }

    void displayVolume()
    {
        cout<<"The volume of object is : " << volume << " m^3" <<endl;
    }

    //destuctor
    ~Box(){
        cout<<"Destructor called."<<endl;
    }
};

int main()
{
    Box cube;                  //creating an object cube of type Box; calls default constructor
    cube.calculateVolume();
    cube.displayVolume();

    Box box(2,3,5);            //creating an object cube of type Box; calls parameterized constructor
    box.calculateVolume();
    box.displayVolume();

    Box same_box(box);         //this creates same_box object with values same as that of box
    box.calculateVolume();
    box.displayVolume();
    return 0;
}

The output of the program is:

The volume of object is : 1000 m^3
The volume of object is : 30 m^3
The volume of object is : 30 m^3
Destructor called.
Destructor called.
Destructor called.

Here, destructor is called 3 times because three objects of class Box have been created. 

Note: Destructor get called in reverse sequence in which objects are created. Here, destructor of cube object gets called first and same_box at last.

C++ Class and Object
C++ static and const