问题
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