1

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).

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Watusimoto
  • 1,773
  • 1
  • 23
  • 38
  • 1
    We are missing information. The assertion hints you're deleting something you're not supposed to delete. Is the object static? Are you sure you didn't delete it before? Are you sure the pointer you delete didn't change its target somewhere in between to something it shouldn't delete? – wilhelmtell Apr 16 '11 at 18:47
  • The code sample above is complete -- running only those three lines will reliably reproduce the problem. You can see there is no delete, and that the target did not change. The object is not static. – Watusimoto Apr 16 '11 at 21:35
  • 1
    Then change your compiler because it sucks. This code as is should not even compile. – wilhelmtell Apr 16 '11 at 22:17

3 Answers3

7
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
};
Nawaz
  • 353,942
  • 115
  • 666
  • 851
5

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 {};
Community
  • 1
  • 1
GManNickG
  • 494,350
  • 52
  • 494
  • 543
3

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.

Xeo
  • 129,499
  • 52
  • 291
  • 397