Delay constructor call

I need to delay the call to the constructor, so I can initialize the value that should be passed to the constructor. I wrote a short and very simplified example.

class A { private: ObjectA* _ptr; public: A(ObjectA*); }; class B { private: A object; // The constructor seems to be called here? ObjectA* obj; public: B(); }; A::A(ObjectA* ptr) { this->_ptr = ptr; } B::B() { obj = new ObjectA(); object(obj); // I want to call the 'A' constructor here, after initializing of 'obj'. } 

Is it possible?

+5
source share
1 answer

No, you cannot defer the construction of a member of a value. You can use a pointer instead of a direct value, but you have no solution for your problem.

The correct solution for your problem is an initialization list :

 B::B ( ) : obj(new ObjectA), object(obj) {} 

In addition, you must put obj before object in class B :

 class B { private: ObjectA *obj; A object; public: B ( ); } 

The reason for this is that when calling the constructor, all elements of the objects must be properly constructed and initialized. This is done using their default constructor.

The reason for the reordering of class members is that member initializers are called in the order in which they are declared in the class, not in the order they appear in the initialization list.

+15
source

All Articles