ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
struct Event {
    virtual void handle() const { cout << "generic-event "; }
};
struct ClickEvent : Event {
    void handle() const override { cout << "click "; }
};
struct Dispatcher {
    vector<Event*> queue;
    void post(Event* e) { queue.push_back(e); }
    void run() { for (auto* e : queue) e->handle(); }
};
int main() {
    Dispatcher d;
    Event e1;
    ClickEvent e2;
    d.post(&e1);
    d.post(&e2);
    d.run();
}
  1. A. generic-event generic-event
  2. B. Compilation error: cannot post a ClickEvent* as Event*
  3. C. generic-event click
  4. D. click generic-event

Correct answer: C. generic-event click

Both &e1 and &e2 are legally stored as Event* (upcasting a derived pointer is implicit). run() dispatches handle() virtually per element in post order: e1 (a real Event) prints "generic-event ", e2 (a real ClickEvent) prints "click ".

More OOP with C++ and Java questions

Exams that ask this topic