Consider this code:
class A {
public:
void fun() {}
};
class B : public A {
public:
void fun() {}
};
int main()
{
A *p = new B;
delete p;
}
Classes A and B are not polymorphic, and neither class declares a destructor. If I compile this code with g++ -Wall
, the GCC compiler happily compiles the code.
But if I add virtual
to void fun()
in A, the compiler issues this warning: "deleting object of polymorphic class type ‘A’ which has non-virtual destructor might cause undefined behavior".
I'm quite aware of the dangers of using non-virtual destructors. But the code above makes me wonder about two things:
- Why do I need to write an empty virtual destructor in the base class when I'm not using destructors at all?
- Why is the empty virtual destructor not required if the base class contains no other virtual functions?
EDIT
It appears that I need to clarify the thing that bothers me:
The above code declares no destructors.
If I declare a virtual function, the compiler complains about the missing virtual destructor. My conclusion: If the class is polymorphic, I need to write a virtual destructor if delete p
is to work correctly.
But if I declare no virtual function (as in the initial example above), the compiler does not complain about a missing virtual destructor. My conclusion: If the class is not polymorphic, I do not need to write a virtual desctructor, and delete p
will work correctly anyway.
But that last conclusion sounds intuitively wrong to me. Is it wrong? Should the compiler have complained in both cases?
B *p = new B;
and everything would be well. – Kerrek SBWhy do I need to write an empty virtual destructor in the base class when I'm not using destructors at all?
All classes have destructors. – PaulMcKenzieA *p = new B; delete p;
is perfectly legal. The question is does it work for non-polymorphic classes? The compiler warns if the class is polymorphic, but not if it is non-polymorphic. Why? – oz1cz