Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay constructor call

I need to delay the constructor call, so I can initialize the value that should be passed to the constructor. I have written 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?

like image 672
BufferOverflow Avatar asked Aug 02 '16 10:08

BufferOverflow


1 Answers

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

The proper solution for your problem is using initialization list:

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

Also, you have to put obj before object in class B:

class B
{
        private:
                ObjectA *obj;
                A       object;

        public: 
                B ( );
}

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

The reason for reordering the class members is that the initializers of the members are called in the order they are declared in the class not in the order of their appearence in the initialization list.

like image 144
Fatih BAKIR Avatar answered Nov 07 '22 05:11

Fatih BAKIR