LearnFrenzy
Sign in Take a free test

Encapsulation · Find the Error · Question 7

Error: protected member via a base-class object Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

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

main.cpp
#include <iostream>

class Account {
protected:
    double balance_ = 1000;
};

class Auditor : public Account {
public:
    void zero(Account& any) { any.balance_ = 0; }
};

int main() {
    Account acc;
    Auditor a;
    a.zero(acc);
    return 0;
}
  • A Auditor must be a friend of main
  • B A derived class may access protected members only through objects of its own type; any is an Account (maybe not an Auditor), so any.balance_ is inaccessible Correct
  • C balance_ must be static
  • D zero must be const
Correct Answer: Option B

Without this rule, anyone could write a class derived from Account just to modify every Account in the program.

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