#include <iostream>
class Event {
public:
virtual void Run(int Param) = 0;
};
// This is a user event and I have no idea what the class name is,
// but I still have to call it's method Run() that is common to the interface "Event"
class UserEvent: public Event {
public:
virtual void Run(int Param)
{
std::cout << "Derived Event Dispatched " << Param << std::endl;
}
};
// This parameter is of pure abstract base class Event because
// I have no idea what my user class is called.
void CallEvent(Event *WhatEvent)
{
std::cout << "in CallEvent(Event *WhatEvent):" << std::endl;
// Huh? WhatEvent = new Event();
// wrong: WhatEvent.Run(123);
// Instead, use ->.
// For pointers, check for non-nullptr is very reasonable:
if (WhatEvent) WhatEvent->Run(123);
// obsolete: delete WhatEvent;
}
// second approach using a reference (as recommended in comments):
void CallEvent(Event &WhatEvent)
{
std::cout << "in CallEvent(Event &WhatEvent):" << std::endl;
WhatEvent.Run(123); // for references - select operator . is fine
}
int main()
{
std::cout << "Hello World!" << std::endl;
/* nullptr does not make sense:
* UserEvent *mE = nullptr;
* Go back to original approach:
*/
UserEvent mE;
CallEvent(&mE); // calling the first (with Event*)
CallEvent(mE); // calling the second (with Event&)
return 0;
}