Reputation:
Assume the following code:
class Event {
public:
virtual void execute() {
std::cout << "Event executed.";
}
}
class SubEvent : public Event {
void execute() {
std::cout << "SubEvent executed.";
}
}
void executeEvent(Event e) {
e.execute();
}
int main(int argc, char ** argv) {
SubEvent se;
executeEvent(se);
}
When executed, the program outputs "Event executed.", but I want to execute SubEvent. How can I do that?
Upvotes: 5
Views: 2204
Reputation: 227608
You are passing the Event
by value. The function gets its own copy of the argument, and this is an Event
object, not a SubEvent
. You can fix this by passing a reference:
void executeEvent(Event& e)
{// ^
e.execute();
}
This is called object slicing. It is the equivalent of this:
SubEvent se;
Event e{se};
e.execute();
Upvotes: 7