LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Find the Error · Question 4

Error: an abstract class as a data member Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

struct Engine { virtual int power() const = 0; virtual ~Engine() = default; };
struct Petrol : Engine { int power() const override { return 110; } };

struct Car {
    Engine engine;
    int power() const { return engine.power(); }
};

int main() {
    Car c;
    std::cout << c.power() << '\n';
    return 0;
}
  • A power must be virtual in Car
  • B A member of abstract type Engine cannot exist; hold a std::unique_ptr<Engine> (or Engine&) to a concrete engine Correct
  • C Car needs a destructor
  • D Petrol is never used
Correct Answer: Option B

Composition with an interface means holding it by pointer or reference, typically injected through the constructor.

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