LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Find the Error · Question 2

Error: a vector of an abstract type Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links