ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
struct Base {
    void greet() { cout << "Base::greet "; }
};
struct Sub : Base {
    void greet() { cout << "Sub::greet "; }
};
void show(Base &b) { b.greet(); }
int main() {
    Sub s;
    show(s);
}
  1. A. Sub::greet
  2. B. Base::greet
  3. C. Compile-time error: greet() is ambiguous
  4. D. Undefined behaviour

Correct answer: B. Base::greet

Neither greet() is virtual, so Sub::greet merely hides Base::greet by name rather than overriding it; there is no dynamic dispatch at all. show(Base &b) statically binds b.greet() to Base::greet based purely on b's declared type, Base&, even though the actual object is a Sub.

More OOP with C++ and Java questions

Exams that ask this topic