For example:
// No virtual methods in Base
class Base
{
public:
Base() {}
~Base() {}
void Foo();
};
// Derived class containing virtual methods -- will this cause problems??
class Derived : public Base
{
public:
Derived() {}
virtual ~Derived() {}
virtual void Bar() {}
};
I've read that declaring at least one virtual (and/or pure virtual) function in a Base class will implicitly cause all Derived classes to apply the virtual keyword to those same (virtual) methods(s) defined in the Base. This makes sense.
Yesterday I read a comment to an answer where @Aaron-McDaid indicated:
... if you have a non-virtual Base class, and you have some virtual methods in your Derived class, then Base *b = new Derived(); delete b; will be undefined behaviour and possibly crash your program. It looks quite safe, but it's not. (It's because b won't point at the 'start' of the Derived object - it will be offset by the space needed for the vtable. Then, the delete will not be operating on exactly the same address as the new, and therefore it's not a valid address to free. If you are going to have virtual methods anywhere, then put a virtual d'tor in the base.
This sounds plausible to me -- does anyone know for certain whether it is accurate? If it is accurate, why doesn't C++ implicitly make a base method (e.g. destructor) virtual to keep the vtable at the front and prevent the undefined behavior?
Is there an example where one would not want this to happen?
EDIT: Is it safe to declare (and use) virtual methods in a derived class if the base class does not contain a virtual method?