Calling a non-virtual function in derived class using a base class pointer

强颜欢笑 提交于 2019-12-24 11:39:13

问题


As noted in this answer:

high reliance on dynamic_cast is often an indication your design has gone wrong.

What I'd like to know is how can I call a custom function in a derived class, for which there is no same-name function in the base class, but do so using a base class pointer and perhaps without dynamic_cast if in fact there is a better way.

If this function was a virtual function defined in both, that's easy. But this is a unique function only in the derived class.

Perhaps dynamic_cast is the best way afterall?


回答1:


In order to call a function of Derived class you have to obtain a pointer to derived class. As an option (depending on situation) you may want using static_cast instead of dynamic, but as you said:

it is often an indication your design has gone wrong

Also, sometimes I think it's ok to use casts. When I was designing a GUI library for a game it has a base class Widget and lots of subclasses. An actual window layout was made in an editor and later some Loader class was inflating this layout. In order to fill widgets from the layout with actual specific for each widget data (game related) I made a method for quering widget's child from a widget. This function retuned Widget* and then I dynamic_casted it to actual type. I have not found a better design for this.

Later I also found that GUI system on Android works the same way




回答2:


What I'd like to know is how can I call a custom function in a derived class ... without dynamic_cast if in fact there is a better way

As indicated in the quote, it's a design issue, not an implementation issue. There's no "better way" to call that function; the "better way" is to redesign your types so that subtypes don't need to add functionality to their parents. By doing so, your types satisfy (a common interpretation of) the Liskov Substitution Principle, and are easier to use since users don't need to know about the subtypes at all.

If it's impossible or unreasonably difficult to redesign the types in such a way, then perhaps you do need RTTI. The advice doesn't say "All use of ...", just "High reliance on ...", meaning that RTTI should be a last resort, not a default approach.




回答3:


This is more like an option then a real answer, so don't stone me to death.

class Derived;

class Base
{
public:

   virtual Derived * getDerived()const
   {
       return NULL;
   }
};

class Derived : public Base
{
public:

   virtual Derived * getDerived()const
   {
       return this;
   }
};

I guess you get the picture...

P.S. Mike Seymour, thanks :-)



来源:https://stackoverflow.com/questions/16566771/calling-a-non-virtual-function-in-derived-class-using-a-base-class-pointer

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