Is it bad design to use dynamic_cast in c++

萝らか妹 提交于 2019-12-23 04:52:59

问题


I have a class CAbstractNode and it has 5 derived classes

out of 5, only 2 (special) need a method SetValue() and a member int nVal;

//myFunction is virtual function of base(cAbstractNode) implemented in 2 special derived classes
myFunction(CAbstractNode * obj, int val)
{
    Derived_02 nodeObj = dynamic_cast<Derived_02*>(obj);

    if(res != NULL)
    {
        nodeObj->setValue(val);
    }

    //remaining code goes here...
}


//myFunction is virtual function implemented in remaining 3 derived classes ( setValue() is not needed here)
myFunction(CAbstractNode * obj, int val)
{

    //remaining code goes here...
}

shall I go with dynamic cast for 2 derived classes (as shown above)

or

shall I take setValue() method as virtual in base(CAbstractNode) and implement in 2 derived classes and this method keeping empty in other 3 derived classes ?


回答1:


Problem is not dynamic_cast itself, it is a symptom. In your case if myFunction accepts CAbstractNode interface it should work with it. But for whatever reason it has to know about Derived_02 and call specific method of that, which most probably shows that CAbstractNode interface is poorly designed. Or at least not properly designed, but it is up to you to decide if you want to fix interface or keep workaround. Remember engineering is mostly about compromises, perfect design quite often is not reachable or not practical.




回答2:


dynamic_cast is a code smell

Usually this can be solved overloading the functions or using virtual functions.



来源:https://stackoverflow.com/questions/43307674/is-it-bad-design-to-use-dynamic-cast-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!