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.
Aucun commentaire:
Enregistrer un commentaire