Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual functions overriding and hiding

Tags:

c++

overriding

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.

like image 206
user152508 Avatar asked Apr 03 '12 10:04

user152508


1 Answers

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.

like image 93
Jon Avatar answered Sep 25 '22 07:09

Jon