Quote:Original post by Endurion
It will, but only if you have a virtual destructor.
Assuming that the code is something like:
#include <iostream>class BaseObject{ int mTemp; public: BaseObject() : mTemp(1) {} ~BaseObject() { std::cout << mTemp << std::endl; } virtual void justForPolymorphism(void){ }};class DerivedObject: public BaseObject{ int mTemp; public: DerivedObject() : BaseObject(), mTemp(2) {} ~DerivedObject() { std::cout << mTemp << std::endl; }};int main(void){ BaseObject* baseObjectPtr = new BaseObject(); DerivedObject* derivedObjectPtr = dynamic_cast<DerivedObject*>(baseObjectPtr ); if(derivedObjectPtr == 0){ std::cout << "CAN'T DYNAMICALLY CAST THE BaseObject POINTER!" << std::endl; } delete baseObjectPtr; // OK, Prints 1 system("PAUSE");}
It will not, in fact, need a virtual destructor in BaseObject to delete the baseObject data. This is because baseObjectPtr is being deleted, not derivedObjectPtr.
However, if the above main function was:
int main(void){ DerivedObject* derivedObjectPtr = new DerivedObject(); BaseObject * baseObjectPtr = derivedObjectPtr; delete baseObjectPtr; // Prints 1 BUT DOES NOT PRINT 2! Did not delete the DerivedObject data! system("PAUSE");}
You would definately need a virtual base destructor in order to delete the derived objects data (and you should always have one, if a class will ever be inherited from).
In reply to the original question then:
1. You cannot just assign a base class pointer to a derived class pointer, you must use dynamic_cast.
1.1 You can't dynamically cast a base object pointer to a derived object pointer, if the data pointed to by the base pointer is not derived object data.
2. Deleting the ptrbase is fine. If ptrbase in fact points to MeshInstance data, then BaseObject MUST have a virtual destructor to destroy the MeshInstance specific data.
3. If assigning ptrbase to ptrmesh (through dynamic_cast) succeeded, then deleting ptrbase will result in ptrmesh pointing to bad data. If you then assigned something else to ptrbase, ptrmesh would still point to bad data.