Question 2
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
#include <iostream>
#include <vector>
struct Task { virtual void run() const = 0; virtual ~Task() = default; };
struct Print : Task { void run() const override { std::cout << "print\n"; } };
int main() {
std::vector<Task> tasks;
tasks.push_back(Print{});
for (const auto& t : tasks) t.run();
return 0;
}
- A run must be public
- B A vector stores elements by value, so std::vector<Task> would need Task objects, which cannot exist; store std::unique_ptr<Task> instead Correct
- C push_back cannot take temporaries
- D Print must be final
Correct Answer: Option B
Polymorphic collections hold pointers (ideally smart pointers) to the abstract type.
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!