Question 12
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
#include <memory>
#include <vector>
struct Shape { virtual double area() const = 0; virtual ~Shape() = default; };
struct Rect : Shape { double w, h; Rect(double a, double b) : w(a), h(b) {} double area() const override { return w * h; } };
struct Tri : Shape { double b, h; Tri(double x, double y) : b(x), h(y) {} double area() const override { return b * h / 2; } };
int main() {
std::vector<std::unique_ptr<Shape>> v;
v.push_back(std::make_unique<Rect>(3, 4));
v.push_back(std::make_unique<Tri>(6, 5));
v.push_back(std::make_unique<Rect>(1.5, 2));
double total = 0;
for (const auto& s : v) total += s->area();
std::cout << total << ' ' << v.size() << '\n';
return 0;
}
- A 30 3 Correct
- B 45 3
- C 27 3
- D 30 2
Correct Answer: Option A
12 + 15 + 3 = 30. The vector stores pointers to the abstract type; the objects are concrete.
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!