CodeBlanks Logo Icon CodeBlanks

private members

Learn information hiding with private members.

private members

Encapsulation is hiding an object's internal data from the outside. In C++ you do this with the private access modifier. A private member can only be accessed from the class's own member functions; it cannot be read or changed directly from outside the class.

Example: class Account { private: int balance; };. Here balance is private. If you write Account a; a.balance = 100; you get a compile error, because balance cannot be reached from outside. This prevents balance from getting invalid values such as negative numbers. Exposing data only through controlled paths catches errors early.

Protecting data

Making a member private not only hides data; it is also the basis for preventing invalid values. By making a member variable private and writing a public method that changes it, you can add checks inside that method.

Example: void setAge(int a) { if (a >= 0) age = a; }. Here age is private. The call setAge(-5) does not allow a negative age; age is not changed. If age were public, you could write w.age = -5; to set an invalid value and no one could stop it. Encapsulation protects the class's invariants.

Practice Add a private member to the Wallet class

Define a Wallet class. Under private: add the int money; member variable. Under public: add void setMoney(int m) { if (m >= 0) money = m; } and int getMoney() { return money; }. In main create an instance, call setMoney(50) and print getMoney() with std::cout.

Starter code

main.cpp
#include <iostream>

// Define the Wallet class here

int main() {
    // Create a Wallet instance, call setMoney and print getMoney
    return 0;
}

Sample solution

main.cpp
#include <iostream>

class Wallet {
private:
    int money;
public:
    void setMoney(int m) {
        if (m >= 0) money = m;
    }
    int getMoney() {
        return money;
    }
};

int main() {
    Wallet w;
    w.setMoney(50);
    std::cout << w.getMoney();
    return 0;
}

Expected output

50

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In class Wallet { private: int money; };, can money be accessed from outside?

main.cpp
class Wallet { private: int money; };
  • Yes, from anywhere
  • No, only from inside the class Correct answer
  • Only from main
  • Only from friend classes

Explanation: A private member can only be accessed from the class's own methods.

2 Write the access modifier

Question
class Account { ____: int balance; public: int getBalance(); };
Answer
class Account { private: int balance; public: int getBalance(); };

Explanation: balance is made private; getBalance is exposed public.

3 Match each modifier to its access

Term Meaning
private Only inside the class
public From anywhere
protected Deriving classes too
int balance; Default private

All lessons in Intermediate