ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
struct Vehicle { virtual string type() { return "Vehicle"; } };
struct Car : Vehicle { string type() override { return "Car"; } };
struct Truck : Vehicle { string type() override { return "Truck"; } };
int main() {
    vector<Vehicle*> v = { new Car(), new Truck(), new Vehicle() };
    for (auto *x : v) cout << x->type() << " ";
}
  1. A. Vehicle Vehicle Vehicle
  2. B. Car Truck Vehicle
  3. C. Car Car Car
  4. D. Compile-time error: cannot store Vehicle* and derived pointers in the same vector

Correct answer: B. Car Truck Vehicle

A vector<Vehicle*> can hold pointers to any Vehicle-derived object; virtual dispatch on type() looks at each pointee's actual class, giving Car for the Car object, Truck for the Truck object, and Vehicle for the plain Vehicle object.

More OOP with C++ and Java questions

Exams that ask this topic