I had this question (beginner C++) in a C++ quiz : My answer was incorrect, I want to understand the explanation behind the correct answer – “Undefined behavior”
Question:
What will happen in the following code after the function foo() returns?
class base
{
public:
base() { }
~base() { }
};
class derived : public base
{
private:
int *p_pi_values;
public:
derived() : p_pi_values(new int[100]) { }
~derived() { delete [] p_pi_values; }
};
void foo(void)
{
derived *p_derived = new derived();
base *p_base = p_derived;
// Do some other stuff here.
delete p_base;
}
I gave this answer which turned out wrong ==> integer array will not be properly deleted.
Correct Answer ==> The behavior is undefined.
The destructor of your base class isn’t
virtual. It’s simply a rule of the language that if you delete an object through a pointer to a base subobject, the corresponding base class must have a virtual destructor, or otherwise it is undefined behaviour.(In practice, if your base class doesn’t have a virtual destructor, the compiler may not emit the necessary code to perform all the necessary clean-up for the derived object. It will just assume that your object is of the same type as the pointer and not bother to look further, as indeed the polymorphic lookup of the most derived object comes at a cost that you don’t want to impose needlessly.)
§5.3.5/3: