C++ Interview

Constructors in C++ and Its Types

Constructors in C++ are special member functions that initializes newly created object of a class. It invoked automatically at the time of object creation.

The name of the C++ constructors has the same name as the class or struct and do not have any return type. If you will not create own constructor then, the compiler creates a default constructor. Also, like another non-static member functions constructor also has the “this pointer” (Address of the object for which it is being called).

Consider the below example,

class TestClass
{
public:
    // Default constructor
    TestClass()
    {
        // Initialize data members here
    }
};

Here, the member function TestClass() is a constructor of the class TestClass(). You can see the above default constructor has the same name as the class and it does not have a return type.

 

If you focused on the above example code then, you would see public access specifier with constructor. But like other class member function you can use different access specifiers with C++ constructors such as public, protected, or private.

In our code generally, we use public access specifier with C++ constructors so objects of the class can be created both inside and outside the class definition.

But if you want you can also declare a constructor as protected or private. A private or protected constructor is used to enforce certain design patterns, restrict object instantiation or encapsulate object creation from specific contexts.

class TestClass
{
protected:
    // Protected constructor
    TestClass()
    {
        // Constructor code
    }
};


class TestClass
{
private:
    // Private constructor
    TestClass()
    {
        // Constructor code
    }
};

 

How does constructor work in C++?

When we create an object of a class then it is responsibility of constructor to initialize the newly created object.

Compiler invoked the constructor automatically for initialization after the memory allocation is done for that object. This initialization happens in two ways initialization lists or constructor body. Initialization lists is a more efficient way to initialize class members than assigning values in the constructor body.

If you want, you can create own constructor to fulfill the requirement. But story is not ending here, C++ also give you facility to create multiple constructors with different parameter lists that means C++ allows constructors to be overloaded.

Consider the below code,

In the below example code, we create own constructor because we need to initialize the class members length, width with a specific value that are 5 and 6 respectively.

We have also implemented two member functions CalculateArea and DisplayArea to calculate the area and to display the calculated area.

You can see the code when the object “box” is created, the length and width of the object are initialized to 5 and 6 respectively.

#include <iostream>

using namespace std;


class Area
{
    unsigned int length;
    unsigned int width;
    unsigned int area;
public:

    Area(int l, int w):length(l),width(w),area(0) //constructor
    {
    }
    void CalculateArea(void)
    {
        area = (length * width);
    }

    void DisplayArea(void)
    {
        cout << "Area = " <<area;
    }

};

int main()
{
    Area box(5,6);
    box.CalculateArea();
    box.DisplayArea();

    return 0;
}

Output:

Area = 30

 

Some important points related to C++ constructors:

  • Constructors do not have names, or you can say constructors name same name as the class name.
class S
{
    S(); // declares the constructor
};

S::S() 
{  
    // defines the constructor
}
  • Constructors are invoked automatically whenever new object is created.
  • Generally, we use public access specifier with C++ constructors.
  • They are used to initialize the objects of its class type. That means constructors initialize the attribute (member variables) to their initial values.
  • The address of a constructor shall not be taken.
#include <iostream>

using namespace std;

class TestClass
{
public:
    TestClass()
    {
        // Constructor code
    }
};

int main()
{
    // Attempting to take the address of the constructor
    // This will result in a compilation error
    TestClass* ptr = &TestClass;

    return 0;
}

 

  • Constructor does not have a return type.
class TestClass
{
public:
    TestClass()
    {

        return 5; //compilation error
    }
};
  • C++ allows overloaded constructors that means a class can have multiple constructors with different parameter lists. A suitable constructor is invoked based on the arguments provided during object creation.
  • Constructors initialize the objects of a class in two ways initialization lists or constructor body.
    1. Member initializing in initialization lists.
class TestClass 
{

 
public:
//member initializer list
  TestClass (int a, string s):age (a), name (s) 
  {
  } 
private:
int age;
string name;
};

2. Member initializing in constructor body.

class TestClass
{

public:
    //member initializing in constructor body
    TestClass (int a, string s)
    {
        age = a;
        name = s;
    }
private:
    int age;
    string name;

};

 

  • Constructors of base class can be called by derived class constructors explicitly through an initialization list.
class Base
{
    public:
  Base (int age, string name)
  {
  }
};

class Derived:public Base
{
    public:
  Derived (int age, string name):Base (age, name)
  {


  }
};

 

  • A constructor shall not be a coroutine.
  • Constructor can not be declared virtual.
  • Constructor can not be declared virtual.

 

Types of Constructors in C++

Mainly in c++ there are three types of constructors exist “Default constructor”, “Parameterized constructors” and “Copy constructor”. We create the constructor as per our requirement but if we will not create the constructor then the compiler automatically creates the constructor to initialize the class object.

Default Constructors:

The default constructor has no parameters. It means it does not takes any arguments and does not return anything, let see example code.

#include <iostream>

using namespace std;


class Test
{
    unsigned int aticle;
    unsigned int world;
public:

    Test()
    {
        aticle = 6;
        world = 27;
    }

    void Display(void)
    {
        cout << " aticle = " << aticle <<endl;
        cout << " world = " << world <<endl;
    }
};

int main()
{
    Test box;
    //called the Display
    box.Display();

    return 0;
}

Output:

aticle = 6
world = 27

 

Parameterized Constructors:

We can pass the arguments in the constructor as per the requirement. It is the reason we can create more than one constructor in the class that means constructor can be overloaded.

Let see the below code in which I am creating a parameterized constructor, one thing remember when creating the parametrized constructor then we have to pass the value at the time of creating the object.

#include <iostream>

using namespace std;


class Test
{
    unsigned int aticle;
    unsigned int world;
public:

    Test( int a,int b)
    {
        aticle = a;
        world = b;
    }

    void Display(void)
    {
        cout << " aticle = " << aticle <<endl;
        cout << " world = " << world <<endl;
    }
};

int main()
{
    Test box(89,93);
    //called the Display
    box.Display();

    return 0;
}

Output: 

aticle = 89
world = 93

 

Copy Constructor:

A copy constructor is a member function that initializes an object using another object of the same class. If you will not create own copy constructor then compiler creates a default copy constructor for you.

Let see an example, where I am creating an object (box2) with the help of another object (box1).

#include <iostream>

using namespace std;


class Test
{
    unsigned int aticle;
    unsigned int world;
public:

    // Parameterized constructor
    Test( int a,int b)
    {
        aticle = a;
        world = b;
    }

    //Copy constructor
    Test(const Test &obj)
    {
        aticle = obj.aticle;
        world = obj.world;
    }

    void Display(void)
    {
        cout << " aticle = " << aticle <<endl;
        cout << " world = " << world <<endl;
    }
};

int main()
{
    Test box1(24,93); //Parameterized constructor will call

    Test box2 = box1; //Copy constructor will call

    //called the Display
    box2.Display();

    return 0;
}

Output:

aticle = 24
world = 93

 

Some Important Questions for you related to the constructor,

  • Is it possible to have Virtual Constructor?
  • What is initialization lists?
  • Can we have more than one constructor in a class?
  • Can a constructor throw an exception?
  • When are copy constructors called?
  • Can a copy constructor accept an object of the same class as parameter, instead of reference
    of the object?

You can also see the list of all C++ interview questions, Click here.