Skip to main content

Most Visited Blog

How to Install minGW C++ compiler for Windows - Cyborg Coding

Delegating Constructor in C++ with example - Cyborg Coding

A delegating constructor in C++ is a constructor that calls another constructor of the same class. This allows for code reuse and can make it easier to maintain your codebase by reducing redundancy.

C++11 and later versions introduced the ability to use the "using" keyword to delegate the construction to a constructor of the same class. This allows the constructor to reuse the logic of the other constructor and can simplify the implementation.

For example:

class MyClass {
private:
    int x;
    int y;
public:
    MyClass(int xVal) : x(xVal), y(0) {}
    MyClass(int xVal, int yVal) : x(xVal), y(yVal) {}
    MyClass() : MyClass(0) {} // delegating constructor
    int getX() { return x; }
    int getY() { return y; }
};

In this example, "MyClass" has three constructors: a parameterized constructor that takes two parameters, "xVal" and "yVal", another constructor that takes one parameter, "xVal" and a default constructor. The default constructor is a delegating constructor which calls the constructor that takes one parameter with a default value of 0.

MyClass myObject1;
MyClass myObject2(10);
MyClass myObject3(10,20);

In this example, myObject1 is created with the default constructor and initializes x and y to 0, myObject2 is created with the constructor that takes one parameter and initializes x to 10 and y to 0, myObject3 is created with the constructor that takes two parameters and initializes x and y to 10 and 20 respectively.

It's worth noting that the delegating constructor must be the first statement in the constructor body and it can only call another constructor of the same class.

In summary, A delegating constructor in C++ is a constructor that calls another constructor of the same class. This allows for code reuse and can make it easier to maintain your codebase by reducing redundancy. C++11 and later versions introduced the ability to use the "using" keyword to delegate the construction to a constructor of the same class, this allows the constructor to reuse the logic of the other constructor and can simplify the implementation.

Comments