Rich
Rich

Reputation:

Delayed constructor in C++

I have been reviewing some code that looks like this:

class A; // defined somewhere else, has both default constructor and A(int _int) defined
class B
{
public:
    B(); // empty
    A a;
};

int main()
{
     B* b;
     b = new B();
     b->a(myInt); // here, calling the A(int _int) constructor,
     //but default constructor should already have been called
}

Does this work? Calling a specific constructor after the default has already been called?

Upvotes: 2

Views: 2282

Answers (4)

Syed Tayyab Ali
Syed Tayyab Ali

Reputation: 3681

you can make another constructor in Class B

B(int _int):a(_int) {}

in that case when you write b = new B(myInt);

Above code will not delay your constructor code of class A.

you dont need to call b->a(myInt)

Upvotes: 2

Richard Corden
Richard Corden

Reputation: 21721

This is not calling the constructor, and this answer covers the only possible explanation for what is happening.

The only standard way to call a constructor on an existing object is to use placement new, (after the previous instance has been destructed):

void foo (A * a) {
  a->~A ();           // Destroy previous instance
  new (a) A(myInt);   // Construct new object in same location
} 

Upvotes: 1

Azder
Azder

Reputation: 4728

You should just call the A(int) constructor from within the B() constructor or make a B(int) constructor that also calls the A(int) one.

The best practice is to have both, the default one to setup a default int for A, and the B(int) one to init A(int).

Upvotes: 0

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 248019

That code does not call a's constructor. It calls A::operator()(int).

But if you explicitly call a constructor on an object that has already been constructed, you're well into undefined behavior-land. It may seem to work in practice, but there is no guarantee that it'll do what you expect.

Upvotes: 15

Related Questions