简体   繁体   中英

upcast to a protected base using dynamic_cast

The book The c++ programming language has this code:

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 nullptr
}

I tried to prove this behavior for better understanding using the following code:

#include <iostream>

class Ival_slider {
public:
    Ival_slider() {
        std::cout << "Ival_slider called" << '\n';
    }
};

class BBslider {
public:
    BBslider() {
        std::cout << "BBslider called" << '\n';
    }
};

class BB_ival_slider : public Ival_slider, protected BBslider {
public:
    BB_ival_slider() {
        std::cout << "BB_ival_slider called" << '\n';
    }
};


int main() {
    BB_ival_slider* p = new BB_ival_slider{};
    Ival_slider* p1 = p;
    Ival_slider* p2 = dynamic_cast<Ival_slider*>(p);
    BBslider* pbb2 = dynamic_cast<BBslider*>(p);
    if (pbb2) {
        std::cout << "true" << '\n';
    }
}

However,

BBslider* pbb2 = dynamic_cast<BBslider*>(p);

seems not to work as expected.

g++ -std=c++11 -O0 -g3 -Wall -c -fmessage-length=0 -o cast.o "..\\\\cast.cpp"
..\\cast.cpp: In function 'int main()':
..\\cast.cpp:29:43: error: 'BBslider' is an inaccessible base of 'BB_ival_slider'
BBslider* pbb2 = dynamic_cast(p);
^
..\\cast.cpp:29:43: error: 'BBslider' is an inaccessible base of 'BB_ival_slider'

I thought dynamic_cast should at least return nullptr. Is the book wrong? I'm using GCC 4.9.2.

dynamic_cast here is no different from static_cast , and the compiler found that the user code is trying to access a protected base, which is illegal. dynamic_cast does not hide or postpone any compile-time error. If a cast can be determined illegal at compile-time, the compiler will never generate any code and rely on you to check that the cast is actually incorrect at run-time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM