after reading casts in C++ I understand that dynamic_cast should retrieve the derived class when it is "lost". The following example proves me wrong. but I quite don't get it:
the attempt to dynamic_cast (B* po = dynamic_cast(&ao);) makes compilation to fail, although an old fashioned cast will make the compilation succeed, and the run will go as expected.
//g++ 5.4.0
#include <iostream>
using namespace std;
class A{
protected:
int x;
A(int _x) : x(_x) {}
public:
A() : x(-1) {}
void p() { cout << "(A) x = " << x << endl; };
~A(){ cout << "destroy A" << endl; }
};
class B : public A{
public:
B() : A(-2) {}
void p() { cout << "(B) x = " << x << endl; };
};
A& f( A& o ) { return o; }
int main()
{
cout << "start\n";
{
B o;
A ao = f(o);
ao.p();
//B* po = dynamic_cast<B*>(&ao); //this fails with following error :
// source_file.cpp:32:37: error: cannot dynamic_cast ‘& ao’ (of type ‘class A*’) to type ‘class B*’ (source type is not polymorphic)
B* po = (B*)(&ao);
po->p();
}
cout << "stop\n";
}
//trace
//
//start
//start
//(A) x = -2
//(B) x = -2
//destroy A
//destroy A
//stop