Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ method overloading: base and derived parameters

After searching around the web I did not manage to find an answer to this question:

I have this overloaded method:

foo(Base* base);
foo(Derived* derived);

In this case "Derived" is a subclass of "Base".
When I call:

foo(new Derived());

I notice that always the first overloaded method is called, while I would like to achieve the opposite result (call the method which takes a "Derived*" object as a parameter).

How to solve this? Thank you.

EDIT:

Ok, this is my actual situation:

I have an UIWidget and a UIScoreLabel class. UIScoreLabel derives from UIWidget. I also have a GameEvent class (Base) and a P1ScoreGameEvent class (Derived).

UIWidget:

virtual void handleGameEvent(GameEvent* e) { printf("ui_widget"); }

UIScoreLabel:

virtual void handleGameEvent(P1ScoreGameEvent* e) { printf("ui_score_label"); }

This is the call:

UIWidget* scoreLabel = new UIScoreLabel();
scoreLabel.handleGameEvent(new P1ScoreGameEvent());

Output:

ui_widget

I don't understand what I'm doing wrong.

like image 287
Michele Avatar asked Apr 17 '14 09:04

Michele


1 Answers

This is because C++ does not support double dispatch. If you declare your variable as Base, it will be treated so. Once you changed its type to Derived, the compiler was able to get its real type and then call the correct method.

To solve this problem you may want to use a Visitor Pattern.

There's a nice discussion about this in this answer.

like image 109
SeeEn Avatar answered Sep 19 '22 23:09

SeeEn