I'm trying to figure out the behaviour of polymorphism with casting. Using the code below, are you able to explain to me why the "child > parent > child" instructions sequence is OK, and the "parent > child" sequence is not (chd3 variable is null after dynamic_cast) ?
#include <iostream>
using namespace std;
class Parent {
public:
virtual void speak() {};
};
class Child : public Parent {
public:
virtual void speak() override {
cout << "Yeah !" << endl;
};
};
int main(int argc, char* argv[]) {
// ----------------------
// child > parent > child : OK
Child* chd1 = new Child;
Parent* prt1 = dynamic_cast<Parent*>(chd1); if (prt1 == nullptr) { cout << "prt1 ERROR" << endl; return 1; }
prt1->speak();
Child* chd2 = dynamic_cast<Child*>(prt1); if (chd2 == nullptr) { cout << "chd2 ERROR" << endl; return 1; }
chd2->speak();
// parent > child : NOK : raises ptrnull value
Parent* prt2 = new Parent;
Child* chd3 = dynamic_cast<Child*>(prt2); if (chd3 == nullptr) { cout << "chd3 ERROR" << endl; return 1; };
// debug
cin.get();
// return
return 0;
}
Thanks a lot !
(Was expecting Parent > child dynamic_cast to be OK, because I found somewhere on the Internet that it would be OK if the classes have polymorphism.)