6

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?

3
  • Create A dynamically in the B constructor and store pointer to it.
    – Ari0nhh
    Commented Aug 2, 2016 at 11:03
  • 5
    For c++17, use std::optional. Or just improve your design. Commented Aug 2, 2016 at 11:04
  • Why can't you just defer creating the object until the value to be used to construct it is initialised? It's not like it is often sensible to create an object and then use it before it is properly initialised.
    – Peter
    Commented Aug 2, 2016 at 11:29

2 Answers 2

16

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.

2
  • 1
    I'd strongly recommend the OP uses std::unique_ptr. That way he doesn't need to worry about managing the memory. Commented Aug 2, 2016 at 12:12
  • 1
    @MartinBonner, for obj of course, buf it's a different topic. Commented Aug 2, 2016 at 12:34
-1

Here is a solution I would use.

class B
{
private:
  char m_aBytes[sizeof(A)];

  A& getA () { return *(A*)m_aBytes; }

public:
  B ()
  {
    ObjectA* objA = new ObjectA ();
    new (m_aBytes) (objA);
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.