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 connected with function overriding and hiding but still doesn't understand the behavior in this code.
Function overloading does not work based on the runtime type of the arguments (which for your argument here is CustomHandler*
) but rather on their static type (which here is Handler*
, as that's what handler
is declared as).
Virtual functions allow you to make function calls based on the runtime type of one object (the one you call the function on). Dispatching calls based on the runtime type of multiple objects is called multiple dispatch; in this instace we 're talking about the most common case of double dispatch. If you want this kind of functionality you are going to have to implement double dispatch or use a library that does it for you.
The Visitor pattern is a pretty common way of doing the implementation; see also Difference betwen Visitor pattern & Double Dispatch.
Finally, you can find a good discussion of Visitor which includes example code (scroll down) here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With