Reputation: 123
Here is a snippet of my c++ code
class A {
public:
virtual void method() {
cout << "A::method" << endl;
}
virtual ~A() {
cout << "A::destructor" << endl;
}
};
class B : public A {
public:
virtual void method() {
cout << "B::method" << endl;
}
virtual ~B() {
cout << "B::destructor" << endl;
method();
}
};
int _tmain()
{
A* a = new B();
a->method();
delete a;
return 0;
}
I've learned that it's not preferable to call any virtual functions from constructors or destructors. In the destructor of the derived class B, I call the virtual function named, "method()".
Here is the output message.
B::method
B::destructor
B::method
A::destructor
It seems to me there is no problem at all. The virtual function knows its object type and printed "B::method()". Is this a kind of undefined behavior that should be avoided?
Upvotes: 2
Views: 797
Reputation: 234685
Conceptually all the virtual functions in B
are accessible in the destructor body, so your code is fine and well-defined as it is.
But your code is extremely brittle: it would be a different matter if there was a child class of B
which had method
overridden. In that case writing B::method();
in the destructor body of B
would be sufficient.
Short answer: calling virtual methods in constructors and destructors is best avoided.
Upvotes: 2