LearnFrenzy
Sign in Take a free test

Encapsulation · Find the Error · Question 3

Error: calling a private helper function from outside Answer, explanation & discussion

  • Find the error
  • Easy
  • 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>
#include <string>

class Password {
    std::string hash_;
    static std::string scramble(const std::string& s) { return std::string(s.rbegin(), s.rend()); }
public:
    explicit Password(const std::string& p) : hash_(scramble(p)) {}
    bool matches(const std::string& p) const { return scramble(p) == hash_; }
};

int main() {
    std::cout << Password::scramble("secret") << '\n';
    return 0;
}
  • A scramble must not be static
  • B scramble is a private member function; outside code cannot call it, even though it is static Correct
  • C Password needs a default constructor
  • D hash_ must be const
Correct Answer: Option B

Access specifiers apply to functions too – including static ones. Helpers are private precisely so their behaviour can change freely.

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