← C++ from Scratch Lesson 39 of 62 · 10 XP

Access specifiers

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

  • public: — accessible to everyone;
  • private: — only to the class's own methods (the default in a class);
  • protected: — to the methods of the class and its descendants (see the lesson about inheritance).
class Wallet {
public:
    void deposit(int x) { if (x > 0) coins += x; }
    bool pay(int x) { if (x > coins) return false; coins -= x; return true; }
    int balance() const { return coins; }
private:
    int coins = 0;        // can't be changed directly from outside: w.coins = -5; is a compile error
};

In a struct everything is public by default, in a class — private. There are no other differences. The convention: struct is for simple sets of data, class is for when an object has rules that need guarding.

Task. Implement Wallet as above. Read commands until the end of the input: deposit N, pay N (print ok or no money), balance (print the balance).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.