Although this question was perfectly answered by James already, I would like to point out one thing:
In proper C++ code, you'll almost never end up working with void
pointers, which means your code would probably look like this:
SubType *p = new SubType;
BaseType* pB = (BaseType*)p;
delete pB;
in this case, even if the BaseType
would have proper virtual constructor, there is still possible undefined behavior if the SubType
is not derived from the BaseType
. Common C-style cast isn't very lucky choice here.
But in case you would use dynamic_cast
, compiler would most likely not let you do that in case that p
doesn't point to object of polymorphic type. And even in case that p
points to object of polymorphic type, but BaseType
wouldn't be base type of SubType
, dynamic_cast
would return NULL
and you could handle this state appropriately:
SubType *p = new SubType;
BaseType* safePtr = dynamic_cast<BaseType *>(p);
if (!safePtr) // p doesn't point to object of type derived from BaseType
... // handle this situation
else // p points to object of polymorphic type derived from BaseType
delete safePtr;