ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
struct Animal {
    virtual ~Animal() {}
    virtual void speak() const { cout << "..."; }
};
struct Dog : Animal {
    void speak() const override { cout << "Woof"; }
};
void announce(const Animal &a) { a.speak(); }
int main() {
    Animal *animals[2];
    animals[0] = new Dog();
    animals[1] = new Animal();
    for (int i = 0; i < 2; i++) announce(*animals[i]);
}
  1. A. WoofWoof
  2. B. ......
  3. C. Woof...
  4. D. ...Woof

Correct answer: C. Woof...

Dereferencing animals[0] (a Dog*) and passing it to announce(const Animal &a) binds a reference, preserving the object's real type and vtable, so speak() dispatches to Dog::speak, printing Woof. animals[1] is a genuine plain Animal object, so it prints the base's own ..., giving Woof...

More OOP with C++ and Java questions

Exams that ask this topic