LearnFrenzy
Sign in Take a free test

Encapsulation · Find the Error · Question 1

Error: using a protected member from main Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

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

main.cpp
#include <iostream>

class Shape {
protected:
    double area_ = 0;
};

class Square : public Shape {
public:
    explicit Square(double s) { area_ = s * s; }
};

int main() {
    Square sq(4);
    std::cout << sq.area_ << '\n';
    return 0;
}
  • A Square needs a destructor
  • B area_ is protected: accessible inside Shape and its derived classes, but not from outside code such as main; add a public area() getter Correct
  • C area_ must be static
  • D double cannot be protected
Correct Answer: Option B

protected opens access to derived classes only, not to users of those classes.

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