LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 19

Storing derived objects in a vector of base objects Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 19 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <vector>

struct Vehicle {
    virtual int wheels() const { return 0; }
    virtual ~Vehicle() = default;
};
struct Car  : Vehicle { int wheels() const override { return 4; } };
struct Bike : Vehicle { int wheels() const override { return 2; } };

int main() {
    Car c;
    Bike b;
    std::vector<Vehicle> by_value{c, b};
    std::vector<const Vehicle*> by_ptr{&c, &b};
    int v = 0, p = 0;
    for (const auto& x : by_value) v += x.wheels();
    for (const auto* x : by_ptr) p += x->wheels();
    std::cout << v << ' ' << p << '\n';
    return 0;
}
  • A 0 6 Correct
  • B 6 6
  • C 0 0
  • D 6 0
Correct Answer: Option A

A vector<Vehicle> stores copies of the Vehicle part only (slicing), so every element reports 0 wheels. A vector of pointers keeps the real objects and dispatches correctly.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links