I know that following code gives compilation error :
class A{ public : virtual void name(){cout<<typeid(this).name()<<endl;}; };
class B:protected A{public : virtual void name(){cout<<typeid(this).name()<<endl;};};
void foo(B* b)
{
A * a = dynamic_cast<A*>(b); //Error : 'A' is an inaccessible base of 'B'
return;
}
But then why in the C++ Stroustrup book (15.4.1) he writes
class BB_ival_slider:public Ival_slider,protected BBslider{ //...
};
void f(BB_ival_slider*p)
{
// ok
BBslider* pbb2 = dynamic_cast<BBslider*>(p); // ok: pbb2 becomes 0
}
Shouldn’t the line be compilation error ?
So either my gcc is wrong in flagging it as compilation error OR the unthinkable, stroustrup typo or most plausibly I have missed something…
The actual quote from 15.4.1 is:
So it would seem that the text describing the code is correct, but for the wrong reasons —
dynamic_castdoesn’t allow accidental violation of the protection of private and protected base classes, but only because using it would be ill-formed and will result in a compiler error, not because using it will yield a null-pointer. And, of course, the code the text is describing is definitely incorrect.Mistakes happen — maybe it will be fixed in the 4th edition of the book. :-]
(Also, note that if
BB_ival_sliderdeclaresfto be afriend, then the code will behave as described in the book. Perhaps thisfrienddeclaration was implied earlier in the chapter, but I don’t have time right now to read over it carefully to check one way or the other.)