ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
struct Animal {
    virtual std::string sound() const = 0;
    void makeSound() const { cout << sound(); }
    virtual ~Animal() = default;
};
struct Dog : Animal {
    std::string sound() const override { return "Woof"; }
};
struct Cat : Animal {
    std::string sound() const override { return "Meow"; }
};
int main() {
    std::vector<std::unique_ptr<Animal>> zoo;
    zoo.push_back(std::make_unique<Dog>());
    zoo.push_back(std::make_unique<Cat>());
    for (auto &a : zoo) a->makeSound();
}
  1. A. WoofMeow
  2. B. Compile-time error: Animal cannot be stored even indirectly since it is abstract
  3. C. MeowWoof
  4. D. Undefined behaviour: calling a pure virtual function

Correct answer: A. WoofMeow

Animal is abstract only in the sense that it cannot be instantiated directly; std::unique_ptr<Animal> can still manage Dog and Cat objects through base-class pointers perfectly well. makeSound() (a concrete, non-pure function) calls the pure-virtual sound(), which dispatches to each object's real override: Woof, then Meow, in push order.

More OOP with C++ and Java questions

Exams that ask this topic