user2512327
user2512327

Reputation:

Passing a subclass object to a function that takes superclass object

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

Answers (1)

juanchopanza
juanchopanza

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

Related Questions