johnbakers
johnbakers

Reputation: 24760

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

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?

Upvotes: 2

Views: 3514

Answers (3)

user1764961
user1764961

Reputation: 693

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 :-)

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254461

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.

Upvotes: 1

Andrew
Andrew

Reputation: 24846

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

Upvotes: 6

Related Questions