I was playing with dynamic_cast
to understand its usage and came up with the code provided below. I used to believe dynamic_cast<D*>(B*)
succeeds if and only if:
B
is a polymorphic type i.e. it has a virtual function ANDD
is derived fromB
But in the code below Base
and NonDerived
classes are not related in above fashion still the dynamic_cast<NonDerived*>(Base*)
succeeds. I was expecting it to fail and return a NULL
instead. Which C++ rule is kicking in here?
I'm using a C++11 conformant compiler.
#include <iostream>
class Base {
public:
virtual ~Base() = default;
};
class Derived: public Base {
public:
void DerivedFun(){
std::cout << "Derived" << std::endl;
}
};
class NonDerived{
public:
void NonDerivedFun(){
std::cout << "NonDerived" << std::endl;
}
};
int main(){
Base *pb = new Derived();
Derived *pd = dynamic_cast<Derived*>(pb); // Expected this to succeed and it did
pd->DerivedFun(); // Prints "Derived" as expected
NonDerived *pn = dynamic_cast<NonDerived*>(pb); // Expected it to fail but it succeeded?
pn->NonDerivedFun(); // Prints "NonDerived", expected this to throw some null pointer exception!!
delete pb;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire