class CBase { };
class CDerived: public CBase { };
CBase b;
CBase* pb;
CDerived d;
CDerived* pd;
pb = dynamic_cast<CBase*>(&d); // ok: derived-to-base
pd = dynamic_cast<CDerived*>(&b); // wrong: base-to-derived
I know the "base to derived " cast is wrong. But what is the inside reason of it? What is logical reason inside? It's hard to remember this without more explanation I guess. thank you!
For the derived to base conversion, you don't need (and generally don't want) to specify a cast explicitly at all:
CDerived d;
CBase *pb = &d; // perfectly fine
The base to derived cast isn't really wrong, though you'd generally prefer to avoid it. The reason behind that is fairly simple: a pointer to base could be pointing to an actual base object or anything derived from it. If you're going to down-cast like this, you generally need to check whether the conversion succeeded. In the specific case you've given, it won't succeed, so what gets assigned (the result of the dynamic_cast
) will simply be a null pointer.
Most of the time, you'd prefer to specify a complete interface to objects of the class in the base class, so you rarely have much need for downcasts.