Why is the (virtual) destructor of the derived class not called when deleting an array through a pointer to the base class?

 

Why is the (virtual) destructor of the derived class not called when deleting an array through a pointer to the base class?



I have an Animal class with a virtual destructor, and a derived class Cat.

#include <iostream>

struct Animal
{
    Animal() { std::cout << "Animal constructor" << std::endl; }
    virtual ~Animal() { std::cout << "Animal destructor" << std::endl; }
};

struct Cat : public Animal
{
    Cat() { std::cout << "Cat constructor" << std::endl; }
    ~Cat() override { std::cout << "Cat destructor" << std::endl; }
};

int main()
{
    const Animal *j = new Cat[1];
    delete[] j;
}

This gives the output:

Animal constructor
Cat constructor
Animal destructor

I don't understand why is the Cat's destructor not called, when my base class destructor is virtual?



Note that whilst a Cat is an Animal, an array of Cats is not an array of Animals. In other words, arrays are invariant in C++, not covariant like they are in some other languages.

So you are up-casting this array and this later confuses the compiler. You must do array delete[] in this case on the correct, original, type - Cat*.

Note that you would have similar issues for the same reason if you allocated an array of 2 or more Cats, cast this to an Animal* and then tried to use the second or subsequent Animal.



Learn more about this post kindly follow this link 


Post a Comment

0 Comments