5

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?

Natan Streppel
  • 5,759
  • 6
  • 35
  • 43
  • 3
    It's called object slicing, one solution is polymorphism. For example, see [What is the slicing problem in C++?](http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c) and [Learning C++: polymorphism and slicing](http://stackoverflow.com/q/4403726/420683) – dyp Nov 16 '13 at 14:11

1 Answers1

7

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();
juanchopanza
  • 223,364
  • 34
  • 402
  • 480