They use dynamic_cast
to show what it does. So, that's the answer to your "why" question.
Otherwise, the explanations given at that web page are incorrect. The resource you are trying to use is either heavily outdated or tied to some specific, poor-quality compiler. The words "The emerging C++ standard..." at the top of the page are a dead giveaway. C++ standard became reality 11 years ago. (Meaning that site is not a good resource for C++ in general and on dynamic_cast
in particular, if that's what you are looking for.)
Here are their class definitions
class A { public: virtual void f( ); };
class B { public: virtual void g( ); };
class AB : public virtual A, private B { };
The cast
AB& abr = dynamic_cast<AB&>(*bp); // they say: succeeds
will not succeed. It will throw a bad_cast
exception, since B
is not a public base class of AB
. dynamic_cast
cannot be used to break protection in downcasts.
The cast
bp = dynamic_cast<B*>(&abr);
will not even compile, since illegal upcasts (breaking protection) are rejected at compile time even by dynamic_cast
(i.e. the code is ill-formed). Note, that dynamic_cast
does nothing special in this case. With upcasts, dynamic_cast
is equivalent to static_cast
or to no-cast-at-all. The above cast will not compile because B
is a private base. The authors seem to incorrectly assume that dynamic_cast
should return null-pointer in this case.
As for ap = &abr
- yes it will work. There's nothing wrong with it, as long a A
is a public base of AB
.