Eric said:
I had thought that what would happen is that the derived class destructor
would not be called but I see you're right about the standard saying the
behavior is undefined. If I make B::~B non-virtual then it runs ok and
B::~B
is not called.. However making B::~B virtual causes it to crash.
Is there any simple explanation of this particular implementation
mechanism
that causes it to crash when B::~B is made virtual?
B contains a vtable, A does not. Therefore the A object embedded in the B
object is offset four bytes from the start of the whole object. Therefore
when you say delete p you are passing a pointer to the deallocation routine
that is different from the pointer that was allocated. At least that seems
to be what is happening on my platform. I bet if you add any virtual
function to A (not a destructor) it will no longer crash. Would still
technically be undefined behaviour of course.
Try this code, with and without the dummy function.
#include <iostream>
using namespace std;
class A
{
//virtual void dummy() {}
};
class B : public A
{
public:
virtual ~B() {}
};
int main()
{
B* b = new B();
A* a = b;
cout << "a = " << a << '\n';
cout << "b = " << b << '\n';
delete a;
}
john