Pergunta

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?

Foi útil?

Solução

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)
{
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top