ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
struct Animal {
    void speak() { cout << "..."; }
};
struct Dog : Animal {
    void speak() { cout << "Woof"; }
};
int main() {
    Dog d;
    Animal &ref = d;
    Dog &dref = d;
    ref.speak();
    dref.speak();
}
  1. A. WoofWoof
  2. B. ...Woof
  3. C. Woof...
  4. D. ......

Correct answer: B. ...Woof

speak() is not virtual, so each call binds statically to the reference's declared type: ref is Animal&, so ref.speak() runs Animal::speak ("..."); dref is Dog&, so dref.speak() runs Dog::speak ("Woof").

More OOP with C++ and Java questions

Exams that ask this topic