Constructors

Note: try all sample codes using http://cpp.sh/

What is constructor?
A constructor is a member function of a class which initializes objects of a class. In C++, Constructor is automatically called when object(instance of class) create. It is special member function of the class.

How constructors are different from a normal member function?

A constructor is different from normal functions in following ways:

§ Constructor has same name as the class itself

§ Constructors don’t have return type

§ A constructor is automatically called when an object is created.

§ If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and has an empty body).

Types of Constructors

1.     Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has no parameters.

// Cpp program to illustrate the

// concept of Constructors

#include <iostream>

using namespace std;

 

class construct

{

public:

    int a, b;

         

        // Default Constructor

    construct()

    {

        a = 10;

        b = 20;

    }

};

 

int main()

{

        // Default constructor called automatically

        // when the object is created

    construct c;

    cout << "a: "<< c.a << endl << "b: "<< c.b;

    return 1;

}

Output:

 a: 10

b: 20

Note: Even if we do not define any constructor explicitly, the compiler will automatically provide a default constructor implicitly. The default value of variables is 0 in case of automatic initialization.

Parameterized Constructors: It is possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object.

// CPP program to illustrate

// parameterized constructors

 

#include<iostream>

using namespace std;

 

class Point

{

    private:

        int x, y;

    public:

        // Parameterized Constructor

        Point(int x1, int y1)

        {

            x = x1;

            y = y1;

        }

     

        int getX()      

        {

            return x;

        }

        int getY()

        {

            return y;

        }

    };

 

int main()

{

    // Constructor called

    Point p1(10, 15);

 

    // Access values assigned by constructor

    cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();

 

    return 0;

}

Output:

p1.x = 10, p1.y = 15

When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly.

 Example e = Example(0, 50); // Explicit call

 

 Example e(0, 50);           // Implicit call

Uses of Parameterized constructor:

1.     It is used to initialize the various data elements of different objects with different values when they are created.

2.     It is used to overload constructors.

Can we have more than one constructors in a class?
Yes, It is
called Constructor Overloading.

Copy Constructor: A copy constructor is a member function which initializes an object using another object of the same class.

Constructor Overloading

Constructor can be overloaded in a similar way as function overloading.

Overloaded constructors have the same name (name of the class) but different number of arguments.

Depending upon the number and type of arguments passed, specific constructor is called.

Since, there are multiple constructors present, argument to the constructor should also be passed while creating an object.


Example 2: Constructor overloading

// Source Code to demonstrate the working of overloaded constructors
#include <iostream>
using namespace std;
 
class Area
{
    private:
       int length;
       int breadth;
 
    public:
       // Constructor with no arguments
       Area(): length(5), breadth(2) { }
 
       // Constructor with two arguments
       Area(int l, int b): length(l), breadth(b){ }
 
       void GetLength()
       {
           cout << "Enter length and breadth respectively: ";
           cin >> length >> breadth;
       }
 
       int AreaCalculation() {  return length * breadth;  }
 
       void DisplayArea(int temp)
       {
           cout << "Area: " << temp << endl;
       }
};
 
int main()
{
    Area A1, A2(2, 1);
    int temp;
 
    cout << "Default Area when no argument is passed." << endl;
    temp = A1.AreaCalculation();
    A1.DisplayArea(temp);
 
    cout << "Area when (2,1) is passed as argument." << endl;
    temp = A2.AreaCalculation();
    A2.DisplayArea(temp);
 
    return 0;
}

For object A1, no argument is passed while creating the object.

Thus, the constructor with no argument is invoked which initialises length to 5 and breadthto 2. Hence, area of the object A1 will be 10.

For object A2, 2 and 1 are passed as arguments while creating the object.

Thus, the constructor with two arguments is invoked which initialises length to l (2 in this case) and breadth to b (1 in this case). Hence, area of the object A2 will be 2.

Output

Default Area when no argument is passed.
Area: 10
Area when (2,1) is passed as argument.
Area: 2

Default Copy Constructor

An object can be initialized with another object of same type. This is same as copying the contents of a class to another class.

In the above program, if you want to initialise an object A3 so that it contains same values as A2, this can be performed as:

....
int main()
{
   Area A1, A2(2, 1);
 
   // Copies the content of A2 to A3
   Area A3(A2);
     OR, 
   Area A3 = A2;
}

You might think, you need to create a new constructor to perform this task. But, no additional constructor is needed. This is because the copy constructor is already built into all classes by default.

Destructors

What  is  destructor?
Destructor is a member function which destructs or deletes an object.

When   is  destructor  called?
A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called 

How destructors are different from a normal member function?
Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything

class String

{

private:

    char *s;

    int size;

public:

    String(char *); // constructor

    ~String();      // destructor

};

  

String::String(char *c)

{

    size = strlen(c);

    s = new char[size+1];

    strcpy(s,c);

}

  

String::~String()

{

    delete []s;

}

Can there be more than one destructor in a class?
No, there can only one destructor in a class with classname preceded by ~, no parameters and no return type.

When do we need to write a user-defined destructor?
If we do not write our own destructor in class, compiler creates a default destructor for us. The default destructor works fine unless we have dynamically allocated memory or pointer in class. When a class contains a pointer to memory allocated in class, we should write a destructor to release memory before the class instance is destroyed. This must be done to avoid memory leak.

Can a destructor be virtual?
Yes, In fact, it is always a good idea to make destructors virtual in base class when we have a virtual function.