Virtual functions overriding and hiding

I have this code:

class Event{}; class CustomEvent:public Event{}; class Handler { public: virtual void inform(Event e ){} }; class CustomHandler : public Handler { public: void inform(CustomEvent e){} }; CustomEvent cEvent; Handler* handler = new CustomHandler; //this calls Handler::inform(Event), not CustomHandler::(CustomEvent) , as I expected handler->inform(cEvent); 

If I change the code to this:

 class Handler { public: virtual void inform(Event e ){} virtual void inform(CustomEvent e){} }; class CustomHandler : public Handler { public: void inform(CustomEvent e){} }; CustomEvent cEvent; Handler* handler = new CustomHandler; //this calls CustomHandler::(CustomEvent) handler->inform(cEvent); 

I read that this is due to overriding and hiding the function, but still do not understand the behavior in this code.

+7
source share
1 answer

Function overloading does not work depending on the type of argument execution time (for your argument, here is CustomHandler* ), but rather on their static type (which is here Handler* , like what handler declared as).

Virtual functions allow you to make function calls based on the runtime type of one object (the one you are calling the function on). Sending calls based on the runtime type of multiple objects is called multiple dispatch; in this case we are talking about the most common case of double dispatch . If you need such functionality, you will have to implement dual submission or use a library that does this for you.

The visitor pattern is a fairly common way to implement an implementation; see also Difference between visitor template and double shipment .

Finally, you can find a good Visitor discussion that includes sample code (scroll down) here .

+9
source

All Articles