Summary: In this tutorial, we will learn what delegating constructor is in C++ and when we should use it in our C++ programs.

What is Delegating Constructor?

When a constructor calls another constructor, it is known as constructor delegation and the constructor which does so is called the delegating constructor.

The feature to delegate a constructor was introduced in C++11. From C++11, a constructor in its initialization list can call another overloaded constructor.

Class(arguments) : Class(arguments) {
   /* statements */ 
}

To delegate, simply call another constructor passing the value in the initialization list.

Let’s see one example for better understanding.

Example:

#include <iostream>
using namespace std;
 
class TestClass {
    private:
        const int myVariable;
 
    public:
        /*This constructor will be called when no argument-
        is passed during the object creation. This constructor-
        to initialize 'myVariable' with default value is calling-
        the parameterized constructor in the initialization list.*/
        TestClass(): TestClass{5} {}
 
        /*This construtor will be indirectly called by the non-
        parametrized constructor or direclty when the argument-
        is specified at object creation.*/
        TestClass(int val) : myVariable{val} {}
 
        void display() {
            cout << "Value of myVariable is: " << myVariable << endl;
        }
};
 
int main() {
    TestClass object1;
    object1.display();
    
    TestClass object2(12);
    object2.display();
    return 0;
}

Output:

Value of myVariable is: 5
Value of myVariable is: 12

In this example, we are initializing the myVariable property in the parameterized constructor.

In case, the user while creating the object of TestClass doesn’t pass any value for myVariable, then the non-parameterized constructor will call the parameterized constructor with value 0.

So in every situation, the myVariable property will always be initialized.

When to use Delegating Constructor in C++?

Delegating the constructor becomes necessary in cases where the class has constructors overloaded and it has to initialize the property of an instance in the initialization list irrespective of whether the value has been passed or not.

For instance, in the above example, we had to initialize the myVariable property in the initialization list because it is a non-static const variable and the non-static const variable in C++ cannot be defined (initialized) inside of the class.

This Post Has 2 Comments

  1. Mark

    This code is wrong and so is the output. the output should be 5 and 12 and the initialization list should be TestClass(int val) : myVariable{val} {}

    1. Adarsh Kumar

      Thanks, Mark for the correction. I have updated the program and output.

Leave a Reply