3

I've looked at a very similar question, but I'm not quite sure I understand the answer. If I delegate a constructor, which initializations from initialization lists occur?

Example:

MyClass::MyClass(int a, int b)
:
MyClass(a, b, NULL),
int1(a),
int2(b),
pOtherClass(NULL)
{
}

MyClass::MyClass(int a, int b, Other *p)
:
int1(a),
int2(b),
pOtherClass(p)
{
     if (pOtherClass == NULL)
     {
         pOtherClass = &DefaultInstance;
     }
}

Here I have to have full initializer lists for both classes due to compiler settings. But what I don't want is:

  1. First constructor(int, int) calls the second constructor(int, int, Other *)
  2. Second constructor assigns a default address to pOtherClass
  3. First constructor's init list assigns pOtherClass to NULL.

The question I linked at the top seems to indicate that this behavior wont occur, but then what is the point of the initializer list in the (int, int) constructor? Just to keep the compiler happy?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
turbulencetoo
  • 3,447
  • 1
  • 27
  • 50
  • 3
    This is invalid code, as the other answer states and as the [compiler shows](http://coliru.stacked-crooked.com/a/c899f8e5a49a9bce). – chris Feb 19 '14 at 16:32
  • hrmmmm, when I have the delegate alone I get errors about members not being present in the init list. As well as `error: MyClass is not a direct base of MyClass`. Perhaps this indicates that we don't use c++11 though, that could be the issue. – turbulencetoo Feb 19 '14 at 16:41
  • 2
    It could be that your compiler doesn't support delegating constructors. – chris Feb 19 '14 at 16:43

1 Answers1

5

According to the C++ Standard

If a mem-initializer-id designates the constructor’s class, it shall be the only mem-initializer; the constructor is a delegating constructor, and the constructor selected by the mem-initializer is the target constructor. The principal constructor is the first constructor invoked in the construction of an object (that is, not a target constructor for that object’s construction). The target constructor is selected by overload resolution. Once the target constructor returns, the body of the delegating constructor is executed. If a constructor delegates to itself directly or indirectly, the program is ill-formed; no diagnostic is required.

So this constructor definition

MyClass::MyClass(int a, int b)
:
MyClass(a, b, NULL),
int1(a),
int2(b),
pOtherClass(NULL)
{
}

is invalid.

Must be

MyClass::MyClass(int a, int b)
:
MyClass(a, b, NULL)
{
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335