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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With