Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


1 Answers

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.

like image 66
jalf Avatar answered Jun 21 '26 07:06

jalf