RTTI used in the down-casting of the base type to derived type:
Question:
Why is it dangerous that the cast a base type pointer/reference to the derived pointer/reference? And how to ensure a safe casting in our application programming.
Answer:
If a pointer or reference is actually representing a base type object, it is really dangerous to do down-casting from the base type to derived type, because the derived may have the memners which do not exist in the base type. The incorrect memory writing/reading will occur under such a situation.
We can use the RTTI to ensure the safe casting, implemented by the "dynamic_cast<derived_type*>".
(Note: RTTI should be applied by the compiler)
Codes example:
class base_type
{
public:
int a;
void set_a(int aa){a = aa;}
};
class derived_type:public base_type
{
public:
int b
void set_b(int bb){b = bb;}
}
void fun(base_type* p_base)
{
int _a=1, _b=2;
derived_type* p_derived = (derived_type*)p_base; // DANGEROUS!!
p_derived->set_b(_b); // Error, If the p_base points to a pure base_type object
// Safe casting:
derived_type* p2_derived;
if (p2_dervided = dynamic_cast<derived_type*>p_base)
{
//If p_base points to a derived_type object, p2_derived != NULL
p2_derived->set_b(_b); //No problem, because *p2_dervied is a real dervied object
}
else
{
cout<<"\n a non-derived class obj reference passed in.";
}
}
Alex Zhang