LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 1

A volume setter that rejects invalid levels Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

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

main.cpp
#include <iostream>

class Volume {
    int level_ = 5;
public:
    bool set(int v) {
        if (v < 0 || v > 10) return false;
        level_ = v;
        return true;
    }
    int get() const { return level_; }
};

int main() {
    Volume v;
    int ok = v.set(8) + v.set(15) + v.set(-1) + v.set(3);
    std::cout << ok << ' ' << v.get() << '\n';
    return 0;
}
  • A 2 3 Correct
  • B 4 -1
  • C 2 8
  • D 1 3
Correct Answer: Option A

Only 8 and 3 are accepted (true converts to 1), and the level ends at the last valid value. The private data can never hold 15 or −1.

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