C ++ / Stroustrup dynamic_cast vulnerability: conversion to a protected base class

I know that the following code gives a 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 does he write in C ++ Stroustrup (15.4.1)

 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 string be a compilation error? Thus, either my gcc is wrong, marking it as a compilation error, OR an unthinkable, strict typo, or, most likely, I missed something ...

+3
source share
3 answers

Actual quote from 15.4.1:

 class BB_ival_slider : public Ival_slider, protected BBslider { // ... }; void f(BB_ival_slider* p) { Ival_slider* pi1 = p; // ok Ival_slider* pi2 = dynamic_cast<Ival_slider*>(p); // ok BBslider* pbb1 = p; // error: BBslider is a protected base BBslider* pbb2 = dynamic_cast<BBslider*>(p); // ok: pbb2 becomes 0 } 

This is an uninteresting case. However, it is comforting to know that dynamic_cast does not accidentally violate the protection of private and protected base classes .

Thus, it seems that the text describing the code is correct, but for the wrong reasons - dynamic_cast does not allow accidental violation of the protection of private and protected base classes, but only because using it would be poorly formed and lead to a compiler error, and not because that using it will give a null pointer. And, of course, the code that describes the text is definitely incorrect.

Mistakes happen - perhaps this will be fixed in the fourth edition of the book .: -]

Please note that if BB_ival_slider declares f be friend , the code will behave as described in the book. Perhaps this friend declaration was mentioned earlier in the chapter, but right now I don’t have time to read it carefully to check, anyway.)
+2
source

Maybe he checked this code, maybe not. (Many authors put unverified code in their books.) If he checked this, keep in mind that not all compilers are created equal. g ++ does not work with error: 'BBslider' is an inaccessible base of 'BB_ival_slider' . clang fails with error: cannot cast 'BB_ival_slider' to its protected base class 'BBslider' . Other compilers: Who knows? Every compiler that I know of has some issues with complying with the standard.

0
source

I think that if I do not find any constructive evidence, I could just say

"Straustrup was wrong" (it sounds scary :()

I don’t think compilers are allowed to freely shed the guts of a class inside (according to a specific standard). If they are not cut with a knife. (evil pointer operation)

0
source

Source: https://habr.com/ru/post/1393238/


All Articles