fork download
  1. #include <iostream>
  2.  
  3. class Event {
  4. public:
  5. virtual void Run(int Param) = 0;
  6. };
  7.  
  8. // This is a user event and I have no idea what the class name is,
  9. // but I still have to call it's method Run() that is common to the interface "Event"
  10. class UserEvent: public Event {
  11. public:
  12. virtual void Run(int Param)
  13. {
  14. std::cout << "Derived Event Dispatched " << Param << std::endl;
  15. }
  16. };
  17.  
  18. // This parameter is of pure abstract base class Event because
  19. // I have no idea what my user class is called.
  20. void CallEvent(Event *WhatEvent)
  21. {
  22. std::cout << "in CallEvent(Event *WhatEvent):" << std::endl;
  23. // Huh? WhatEvent = new Event();
  24. // wrong: WhatEvent.Run(123);
  25. // Instead, use ->.
  26. // For pointers, check for non-nullptr is very reasonable:
  27. if (WhatEvent) WhatEvent->Run(123);
  28. // obsolete: delete WhatEvent;
  29. }
  30.  
  31. // second approach using a reference (as recommended in comments):
  32. void CallEvent(Event &WhatEvent)
  33. {
  34. std::cout << "in CallEvent(Event &WhatEvent):" << std::endl;
  35. WhatEvent.Run(123); // for references - select operator . is fine
  36. }
  37.  
  38. int main()
  39. {
  40. std::cout << "Hello World!" << std::endl;
  41. /* nullptr does not make sense:
  42.   * UserEvent *mE = nullptr;
  43.   * Go back to original approach:
  44.   */
  45. UserEvent mE;
  46. CallEvent(&mE); // calling the first (with Event*)
  47. CallEvent(mE); // calling the second (with Event&)
  48. return 0;
  49. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Hello World!
in CallEvent(Event *WhatEvent):
Derived Event Dispatched 123
in CallEvent(Event &WhatEvent):
Derived Event Dispatched 123