Encapsulation
Marking a member private prevents code outside the class from touching it directly — the class can then guarantee its own invariants, since the only way to change its state is through the methods it chooses to expose. A method marked const promises not to modify the object it's called on, which the compiler checks and enforces.
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance;
public:
BankAccount(double initial) {
balance = initial;
}
double getBalance() const {
return balance;
}
void deposit(double amount) {
balance += amount;
}
};
int main() {
BankAccount account(100.0);
account.deposit(50.0);
cout << "Balance: " << account.getBalance() << endl;
return 0;
}Balance: 150
balance can never be set to an invalid value from outside BankAccount, because nothing outside the class can reach it directly — every change has to go through deposit, which the class controls completely.
Next: inheritance and polymorphism — building a class hierarchy, and dispatching to the right override at runtime.
Practice exercise
Define a class Temperature with a private double celsius, a constructor that sets it, and a const method getFahrenheit() that returns celsius * 9.0 / 5.0 + 32.0. Create a Temperature with celsius 100.0 and print its Fahrenheit value.