Before C++11, common initializations in multiple constructors of the same class could not be concentrated in one place in a robust, maintainable manner. To partially alleviate this problem in the existing C++ programs, you could use assignment instead of initialization or add a common initialization function.
With the delegating constructors feature, you can concentrate common initializations and post initializations in one constructor named target constructor. Delegating constructors can call the target constructor to do the initialization. A delegating constructor can also be used as the target constructor of one or more delegating constructors. You can use this feature to make programs more readable and maintainable.
Delegating constructors and target constructors present the same interface as other constructors. Target constructors do not need special handling to become the target of a delegating constructor. They are selected by overload resolution or template argument deduction. After the target constructor completes execution, the delegating constructor gets control back.
#include <cstdio>
struct X {
const int i;
X(int x, int y) : X(x+y) { }
X(int x, int y, int z) : X(x*y*z) {}
X(int x) : i(x) { }
};
int main(void){
X var1(55,11);
X var2(2,4,6);
std::printf("%d, %d\n", var1.i, var2.i);
return 0;
}
The output of the example is:66,48
struct A{
int x,y;
A():A(42){}
A(int x_):A() {x = x_;}
};
In the example, there is an infinitely recursive cycle
that constructor A() delegates to constructor A(int
x_), and A(int x_) also delegates to A().
The compiler issues an error to indicate the violation.