LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 15

A private static helper used by public functions Answer, explanation & discussion

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

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

main.cpp
#include <iostream>
#include <string>

class Username {
    std::string value_;
    static bool valid(const std::string& s) {
        if (s.size() < 3 || s.size() > 12) return false;
        for (char c : s) if (!(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && c != '_') return false;
        return true;
    }
public:
    bool set(const std::string& s) { if (!valid(s)) return false; value_ = s; return true; }
    const std::string& get() const { return value_; }
};

int main() {
    Username u;
    std::cout << u.set("ab") << u.set("Asha") << u.set("asha_99") << u.set("a b c") << ' ' << u.get() << '\n';
    return 0;
}
  • A 0010 asha_99 Correct
  • B 0110 Asha
  • C 0011 a b c
  • D 1010 asha_99
Correct Answer: Option A

Too short, an uppercase letter and spaces all fail validation; only asha_99 is accepted. The helper is private: it is an implementation detail of the class.

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