speendo speendo - 5 months ago 27
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,
is initialized with a value of
, which is initialized in the line below. So how would
return a valid value?

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


If _objectA is declared like

class ClassC
    ClassA _objectA;
    ClassB _objectB;


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.