Possible Duplicate:
When to use virtual destructors?
[Second dicuss]
hi,guys! You are all talking about virtual-destructor.
And also i think about the base class`s destructor.
But another test as this:
class A
{
public:
A()
{
}
virtual void fun()
{
}
private:
int mIntA;
};
when class A have a vitual function(not virtual-destrcutor),
it`s ok. Deleting ptrA is OK!
So, i think A just need a vptr to activate the polymorphic. Not class Ass destructor being not virtual just can make resources is not released
destructor must be virtual.
Class A
correctly.
class A
{
public:
A()
{
}
/*virtual*/ ~A()
{
}
private:
int mIntA;
};
class B : public A
{
public:
B()
{
mIntB = 1234;
}
virtual ~B()
{
int i = 0;
}
private:
int mIntB;
};
I have a class A. And a class B derived form A;
A doesn`t have any virtual function.
so when i do this:
A* ptrA = new B;
delete ptrA;
it crashes!
but when add a virtual fun to A. it`s ok.
as we know, ptrA is a B object.
but why is it?
The A class isn’t polymorphic, therefore the delete has no possibility to know that
ptrAactually points inside an allocated block and therefore the deallocation crashes.