LearnFrenzy
Sign in Take a free test

OOPS Concepts · Find the Error · Question 3

Error: calling a non-const member on a const object Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

class Clock {
    int hour_ = 9;
public:
    int hour() { return hour_; }
};

int main() {
    const Clock c;
    std::cout << c.hour() << '\n';
    return 0;
}
  • A hour_ must be static
  • B hour() is not marked const, so it cannot be called on a const object; declare int hour() const Correct
  • C const objects cannot be created
  • D cout cannot print hour
Correct Answer: Option B

Mark every member function that does not modify the object as const – it makes the class usable through const references.

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