3

Will this work, or will there be slicing (i.e. only the memory corresponding to that occupied by a Base object will be freed, rather than for the whole Derived object):

Base* ptr = new Derived;
delete ptr;

If not, will this?

delete static_cast<Derived*>(ptr);
d7samurai
  • 3,086
  • 2
  • 30
  • 43
  • 4
    If the destructor of `Base` is `virtual`, everything will be okay. The compiler will most likely warn you if this is not the case. – arne Jan 16 '14 at 13:29
  • 3
    http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors – Daniel E. Jan 16 '14 at 13:37

2 Answers2

3

This will work.

Calling methods of a derived object by a base object pointer, is one of polymorphism fundamentals.

However, be sure that the base class destructor is virtual, to properly destruct your object.

Axel Borja
  • 3,718
  • 7
  • 36
  • 50
0

this is not a object slicing . Object slicing happens when you cast a derived object to base object .Here you are manipulating a pointer . you can always make base class destructor virtual will make sure that the objects are deleted in the opposite order of creation

Simal Haneef
  • 179
  • 5