C++11 Delegating Constructors

C++ 11 introduces a new feature called “delegating constructors”. Now you can do common initialization steps in a constructor, known as the target constructor. Other constructors can call the target constructor to do the initialization. These constructors are called delegating constructors.


class A{
public:
A(): A(0) {}
A(int i): A(i, 0) {}
A(int i, int j)
{
...
}
...
};

Delegating constructors cannot have initializations of class members in their initializer lists; that is, a constructor cannot delegate and intialize at the same time.

If an exception occurs in the body of a target constructor, it can be caught by the try block of the delegating constructor.


class A{
public:
A();
A(int i);
A(int i, int j);
};
A::A() try: A(0) {
cout << "A() body"<< endl; } catch(...) { cout << "A() catch"<< endl; } A::A(int i) try : A(i, 0){ cout << "A(int i) body"<< endl; } catch(...) { cout << "A(int i) catch"<< endl; }

This feature helps to reduce the code size and make your program more readable and maintainable.

Leave a Reply