Delegate Constructor C++

You need to do the second. Delegating constructors only works in the constructor's initialization list, otherwise you'll just create a temporary or do other mistakes like you mentioned.


The second example using the initializer list is the correct one . First example is going to end up creating a temporary object.


If you want to use constructor delegation after some imperative logic, you can opt to move-assign *this from a temporary:

Foo() {
  // calculate stuff…
  *this = Foo(stuff, calculated, above);
}

The correct syntax is

struct Foo {
  Foo(char x, int y) : _x{x}, _y(y) {}
  Foo(int y) : Foo('a', y) {}

  char _x;
  int _y;
};

Your first example creates a temporary that is destroyed right away.

Tags:

C++

C++11