Whilst studying inheritance in C++, I have learned that a base class intended for polymorphic behavior should implement it's destructor as virtual
I thought I understood how to apply this well, but I have encountered a small problem which I do not understand.
Given the following code:
#include <iostream>
struct Base
{
Base() { std::cout << "Base ctor called\n"; };
virtual ~Base() { std::cout << "Base dtor called\n"; };
};
struct Derived : Base
{
Derived() : Base() { std::cout << "Derived ctor called\n"; }
~Derived() { std::cout << "Derived dtor called\n"; };
};
int main()
{
Derived d;
Base *p_base = &d;
delete p_base; //Problem here?
return 0;
}
Output is as expected:
Base ctor called
Derived ctor called
Derived dtor called
Base dtor called
However, a _CrtisValidHeapPointer(block)
assertion error occurs.
Everything works fine if p_base
points directly to a new Derived
object i.e. Base *p_base = new Derived();
What is different here?
Kind regards