1 2 3
| CParent *pParent = new CParent;
pChild = static_cast<CChild *> (pParent);
pChild->print(); |
This is a BAD idea - you are right in Undefined-Behaviour-Land. Casts are unnecessary when you want to convert from child to parent, but they are very much needed when you convert from parent to child.
static_cast doesn't, cannot verify that the parent pointer you gave it really points to a child or not. All it can check is that the parent and child classes are related. It doesn't check the object - that's the job of
dynamic_cast.
Here you're "lucky" because your print function doesn't actually rely on any of the child class properties that aren't already present in parent.
But what if print were to call virtual member functions of child that do not exist in parent? The compiler would blindly go access inexistant vtbl entries, happily sending your program on a one-way trip to Segfault-Land. And that's if you're lucky.
If you're unlucky, the member function will write to some child member variable that doesn't exist in parent, therefore writing outside the object, either in memory you do not own, causing your application to Segfault (again, if you're lucky), or will overwrite another object's data (if you aren't). If your object is on the stack, you may even end up wiping out your stack frame, which is never a good thing. If the data you're writing comes from user input, you're offering crackers a gigantic security hole on a silver platter for them to exploit.
Partager