C++
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.
Exercise 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.
Show example solution
#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;
}
Test yourself
-
In class Wallet { private: int money; };, can money be accessed from outside?
class Wallet { private: int money; };
- Yes, from anywhere
- No, only from inside the class
- Only from main
- Only from friend classes
Show answer
No, only from inside the class — A private member can only be accessed from the class's own methods.
-
Write the access modifier
class Account { ____: int balance; public: int getBalance(); };
Show answer
class Account { private: int balance; public: int getBalance(); };
-
Match each modifier to its access
- private
- Only inside the class
- public
- From anywhere
- protected
- Deriving classes too
- int balance;
- Default private
Next lesson: Getters and setters