Quoted from C++ Primer 5th 19.2.1. The dynamic_cast Operator
A dynamic_cast has the following form:
dynamic_cast<type*>(e)
dynamic_cast<type&>(e)
dynamic_cast<type&&>(e)
where type must be a class type and (ordinarily) names a class that has virtual functions. In the first case,
e
must be a valid pointer (§ 2.3.2, p. 52); in the second,e
must be an lvalue; and in the third,e
must not be an lvalue.In all cases,the type of
e
must be either a class type that is publicly derived from the target type, a public base class of the target type, or the same as the target type. Ife
has one of these types, then the cast will succeed. Otherwise, the cast fails.
If a dynamic_cast to a pointer type fails, the result is 0. If a dynamic_cast to a reference type fails, the operator throws an exception of typebad_cast
However,here I've written a code snippet:
struct A {};
struct B : private A // note: *private* inheritance
{
A* test() {
return dynamic_cast<A*>(this);
}
};
int main()
{
B b;
if(b.test()==nullptr)
throw 1;
}
In the code snippet above, A
is just a private base of B
, which is not taken into account by the c++ primer. However, this code snippet could be compiled and run without error. Has the primer made a mistake?