using namespace std;
class Animal{
public:
virtual void cry() = 0;
void eat();
};
class Cat:public Animal
{
public:
virtual void cry();
void grooming();
};
class Dog:public Animal
{
public:
virtual void cry();
void lash();
};
main()
{
Animal* animal = new Cat();
animal->eat();
animal->cry();
Cat* cat = (Cat*)animal;
cat->grooming();
Dog* dog = new Dog();
dog->cry();
dog->eat();
dog->lash();
delete animal; //Delete called on'animal' that is abstract but has non-virtual destruct
delete cat; //Thread 1: signal SIGABRT
delete dog;
}
The delete is causing an error. Why is that?
Attempt to release memory via delete without using destructors, but an error occurs
"Delete called on’animal’ that is abstract but has non-virtual destruct
Thread 1: signal SIGABRT"
2
Answers
The error is telling you what the issue is. You are destroying your virtual objects with a non-virtual destructor.
You have
virtual void cry
why? Its so that when you callanimal->cry
, it calls theCat
cry, not the defaultAnimal
cry. The same is true of the virtual destructor. When you calldelete animal
you need it to call the destructor of the actual object, not just the base class. You need to add:to your animal class.
Cpp Core Guidelines
As for the second issue, the double delete:
Some suggest to not delete twice, i would suggest to not call delete explicitly at all. Use a smart pointer:
Unique pointer will handle the deletion of the object for you.
You are trying to delete the same object twice: