ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
struct Animal {
    void speak() { std::cout << "Animal"; }
};
struct Dog : Animal {
    void speak() { std::cout << "Dog"; }
};
int main() {
    Animal *a = new Dog();
    a->speak();
}
  1. A. AnimalDog
  2. B. Dog
  3. C. Animal
  4. D. Compilation error

Correct answer: C. Animal

speak() is not declared virtual, so the call is resolved statically using the pointer's declared type (Animal*), not the object's dynamic type. No vtable is involved, so Animal::speak runs.

More OOP with C++ and Java questions

Exams that ask this topic