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();
}- A. generic-event generic-event
- B. Compilation error: cannot post a ClickEvent* as Event*
- C. generic-event click
- 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
- A lambda expression captures a local variable from its enclosing method. What restriction does Java place on that variable?
- In Java, instance method calls (non-static, non-private, non-final) use dynamic dispatch based on the object's actual run-time class…
- What is printed? cpp struct Vec2 { int x, y; Vec2 operator+(const Vec2& o) const { return {x + o.x, y + o.y}; } }; int main() { Vec2 a{1…
- A base class has a non-virtual destructor. A derived class owns a dynamically allocated member that it frees in its own destructor. What…
- java interface Greet { default String hello() { return "Hi"; } } class English implements Greet {} class French implements Greet { public…
- Why is operator<< for printing a user-defined type usually written as a free function (often declared a friend), rather than as a member…