문제

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top