Pijusn
Pijusn

Reputation: 11293

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?

Upvotes: 7

Views: 6436

Answers (4)

sharptooth
sharptooth

Reputation: 170499

Yes, if class Object (the base class) destructor is declared virtual, otherwise you run into undefined behavior which you don't want.

Upvotes: 0

RedX
RedX

Reputation: 15175

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
}

Upvotes: 21

NPE
NPE

Reputation: 500347

What you describe is precisely the situation where virtual destructors come in. Read the C++ FAQ.

Upvotes: 3

AProgrammer
AProgrammer

Reputation: 52284

If the destructor of Object is virtual, yes.

Upvotes: 7

Related Questions