Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ deleting inherited class

Let's say there is a class Object and then another class Cat that inherits Object. Next, there is a list of Object* (pointers). Then, I create a new Cat and put it into the list. After some time I want to delete all Cats and call delete on each member of the list. Does it call destructor of Cat?

like image 945
Pijusn Avatar asked Jun 07 '11 13:06

Pijusn


1 Answers

Yes if you marked the destructor of object as virtual.

class Object {
  public:
  virtual ~Object(){} //make the base class destructor virtual
};

class cat : public Object {
  public:
  virtual ~cat(){} // now this gets called when a pointer to Object that is a cat is destroyed
}
like image 54
RedX Avatar answered Oct 09 '22 23:10

RedX