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.
سؤال
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);
المحلول
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.
نصائح أخرى
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