speendo speendo - 22 days ago 7
C++ Question

Constructor Initializer List - will this work?

With your help I could solve the problem I described in this minimal example (use parameterized constructor in other classes constructor) using a constructor initializer list.

In my real life problem, things are a bit more difficult. My constructor now looks somehow like this:

ClassC::ClassC() : _objectB(_objectA.getInt()) {
_objectA = ClassA();
}


Will this work? The compiler doesn't return any errors. However,
_objectB
is initialized with a value of
_objectA
, which is initialized in the line below. So how would
_objectA.getInt()
return a valid value?

If it doesn't work, how can I make it work?

Answer

If _objectA is declared like

class ClassC
{
    ClassA _objectA;
    ClassB _objectB;

    public:
    ClassC();
}

it will work, because _objectA is already initialized (with the default constructor), and you just reassign it a new class later, which has nothing to do with _objectB initialization.


However, as @πάντα ῥεῖ suggested it is better to use

ClassC::ClassC() : _objectA(), _objectB(_objectA.getInt()) {}

that will initialize _objectA, then use it for _objectB initialization.