LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 2

Reading another object's private member Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

What is the output of the following C++ program?

main.cpp
#include <iostream>

class Score {
    int pts_;
public:
    explicit Score(int p) : pts_(p) {}
    Score better(const Score& o) const { return pts_ >= o.pts_ ? *this : o; }
    void absorb(Score& o) { pts_ += o.pts_; o.pts_ = 0; }
    int pts() const { return pts_; }
};

int main() {
    Score a(40), b(65);
    Score c = a.better(b);
    a.absorb(b);
    std::cout << c.pts() << ' ' << a.pts() << ' ' << b.pts() << '\n';
    return 0;
}
  • A 65 105 0 Correct
  • B 40 105 0
  • C 65 40 65
  • D Compilation error
Correct Answer: Option A

Access is checked per class, so member functions may use o.pts_ of any Score. c is a copy of b (65); then a takes b's points.

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