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?
Cat(void)
onlyCat()
will work. – LucillelucinaAnimal::~Animal
is not virtual (godbolt.org/z/eKndcKGbM) – Giacinta#define virtual
somewhere? Check with#ifdef virtual \n #error "virtual is defined" \n #endif
– KalbCat(void)
vs.Cat()
thing—in C, you should use the former (thevoid
distinguishes between unspecified and empty arity), but in C++ it's an oxymoron (this cruft has been sensibly removed) and you should use the latter. Highly recommended reading: softwareengineering.stackexchange.com/a/287002 – Slightlynew[]
in a variable declared withconst auto
should keep the type and value ofj
appropriate for use withdelete[]
, and the code would work as expected. It's (almost) no use trying to find a sensible reason for a specific behaviour in presence of UB. It resorts to compiler psychology, not logic. – Cleavers