Code:
A anA;
anA.num = 5;
B aB;
ab.num = 1;
ab.num2 = 2;
anA = (A)aB;
this code creates a new instance of a new A object.
To keep a B object and change only a pointer yo have 2 choices.
Code:
A anA;
anA.num = 5;
B *aB = dynamic_cast<B*>(&anA);
ab->num = 1;
ab->num2 = 2;
//or
A anA;
anA.num = 5;
B &aB = dynamic_cast<B&>(anA);
ab.num = 1;
ab.num2 = 2;
This is how you keep the original object that use inheritance to handle different pointers.
To could also use static_cast, but it could cause a runtime-error if the class instance to be casted isn't the of the type of the cast. To prevent that kind of errors there is dynamic_cast which return NULL is the original object can«t be casted. Therefore you can only use dynamic_cast with pointers, not with objects os references.
Plus, dynamic_cast checks the type of the object at runtime. To do so the dynamic_cast need info which will help in determinig is the class is valid. I don't kno what the standard says about this, but for MS compilers, each class much have at least a virtual method non-pure. The vtable will be used for comparison at runtime.