Where are delegating constructors useful ?

Hi ppl,

I just came across this concept of 'delegating constructors' introduced from c++ 11.

I was wondering in which scenarios these are useful.

I understand that this could be used by other constructors and code repetition can be avoided but other than this, are they useful in any other cases ?

Thanks :)
A "delegating constructor" is, first and foremost, a constructor. More specifically, it's a constructor that offloads the initial part of the object's construction to another constructor (the "target" constructor). There are no other scenarios in which they can be used.
1
2
3
4
5
6
7
class A {
    int x, y;
public:
    A() : A(0) {}                     // delegating ctor
    A(int x) : A(x, 0) {}             // delegating ctor (and target or delegating ctor)
    A(int x, int y) : x(x), y(y) {}   // target of a delegating ctor
};

It's to reduce code repetition. So that if you need to change a feature, you only need to change it in one place instead of five places. That's pretty much the gist of it :)

It's better than having an equivalent Init() function because by the time Init() is called, all class member variables are already constructed (default constructed if you did not explicitly use the initializer list).
Last edited on
Thanks :). Pretty clear now.
Topic archived. No new replies allowed.