LearnFrenzy
Sign in Take a free test

Classes and Objects · Find the Error · Question 2

Error: a const member function changing a member Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

class Player {
    int score_ = 0;
public:
    void add(int pts) const { score_ += pts; }
    int score() const { return score_; }
};

int main() {
    Player p;
    p.add(10);
    std::cout << p.score() << '\n';
    return 0;
}
  • A score_ must be static
  • B add is marked const but modifies score_; remove const from add (it is a modifying operation) Correct
  • C pts must be a reference
  • D score() cannot be const
Correct Answer: Option B

A const member function promises not to change the object. Only queries should be const.

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