Watusimoto
Watusimoto

Reputation: 1888

New, delete, and subclasses in C++

TextItem is a subclass of XObject.

I am trying to figure out why the following works:

  TextItem *textItem = new TextItem();
  XObject *xItem = textItem;
  delete textItem;

But this does not:

  TextItem *textItem = new TextItem();
  XObject *xItem = textItem;
  delete xItem;

The second example fails on delete, with an assertion failure (_BLOCK_TYPE_IS_VALID).

Upvotes: 1

Views: 1075

Answers (3)

Xeo
Xeo

Reputation: 131867

Does XObject not provide a virtual destructor? When you don't have a virtual destructor, you will get undefined behaviour when deleting the TextItem through a base pointer.

Upvotes: 3

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361732

XObject *xItem = textItem;
delete xItem;

This would work only if XObject has virtual destructor. Otherwise, the delete statement invokes undefined behavior.

class XObject
{
    public:
       virtual ~XObject();
     //^^^^^^ this makes virtual destructor
};

Upvotes: 7

GManNickG
GManNickG

Reputation: 504273

Make sure that XObject has a virtual destructor, or your second snippet has undefined behavior:

struct XObject
{
    // now deleting derived classes
    // through this base class is okay
    virtual ~XObject() {}
};

struct TextItem : XObject {};

Upvotes: 5

Related Questions