EverSpring working shop

To pursue creative ideas based on nature.

统计

留言簿(1)

他山之石

阅读排行榜

评论排行榜

RTTI and Down-Casting

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
 

posted on 2008-01-19 23:57 everspring79 阅读(210) 评论(0)  编辑 收藏 引用 所属分类: Questions


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理