I changed my C++ base class to be protected
inheritance and my dynamic_cast
(s) stopped working.
Why should changing the inheritance to protected
change the behavior of dynamic_cast
?
struct Base {
static Base *lookupDerived(); // Actually returns a Derived * object.
};
struct Derived : protected /* Switch this to public to get it working */ Base {
static void test() {
Base *base = lookupDerived();
if (dynamic_cast<Derived *>(base)) {
std::cout << "It worked (we must be using public inheritance)." << std::endl;
} else {
std::cout << "It failed (we must be using protected inheritance)." << std::endl;
}
};
See Question&Answers more detail:os