LearnFrenzy
Sign in Take a free test

Abstraction · Find the Error · Question 8

Error: returning an interface by value Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

struct Shape {
    virtual double area() const = 0;
    virtual ~Shape() = default;
};
struct Square : Shape {
    double s = 2;
    double area() const override { return s * s; }
};

Shape make_shape() { return Square{}; }

int main() {
    std::cout << make_shape().area() << '\n';
    return 0;
}
  • A area must not be const
  • B An abstract class cannot be a by-value return type; return std::unique_ptr<Shape> (or a reference to an existing object) instead Correct
  • C Square must be final
  • D s must be private
Correct Answer: Option B

Factories that hide the concrete type return smart pointers to the interface.

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