C++ OOP Introduction
Object-oriented programming (OOP) is a way to organise programs around objects: things that hold data and know how to work with it. A bank account object holds a balance and knows how to deposit and withdraw. C++ supports OOP with classes, and it is one of the main reasons C++ is used for big programs.
Procedural and object-oriented
In a procedural program, data and the functions that work on it are separate: a struct Account and free functions deposit(Account&, double), withdraw(Account&, double). Nothing stops some other code from changing the balance directly, perhaps to a negative value.
In an object-oriented program, the data and its functions live together in a class, and the class decides who may touch the data:
#include <iostream>
class Account {
double balance = 0; // private: only Account's own functions can change it
public:
void deposit(double amount) {
if (amount > 0) balance += amount;
}
bool withdraw(double amount) {
if (amount > balance) return false;
balance -= amount;
return true;
}
double getBalance() const { return balance; }
};
int main() {
Account acc;
acc.deposit(500);
if (!acc.withdraw(800)) std::cout << "Not enough money\n";
acc.withdraw(200);
std::cout << "Balance: " << acc.getBalance() << "\n";
return 0;
}Not enough money Balance: 300
The balance can only change through deposit and withdraw, which check every change. The rest of the program cannot break the account.
The four ideas of OOP
- Encapsulation: keep data private and offer a small set of public functions. The class protects its own rules.
- Abstraction: users of a class only need to know what it does, not how. You use
std::stringwithout knowing how it stores the text. - Inheritance: build a new class on an existing one, reusing its code (a
SavingsAccountis anAccountthat also pays interest). - Polymorphism: one piece of code works with many kinds of objects, each behaving in its own way (every shape knows its own area).
The next topics take these one at a time: Classes and Objects, Class Methods, Constructors, Access Specifiers, Inheritance and Polymorphism.
When OOP helps
OOP shines when a program models many kinds of things with their own rules: accounts, players, shapes, devices. It is not the only style: C++ also supports plain functions and generic programming with templates, and good C++ code mixes them. A small calculation does not need a class; a game with dozens of kinds of objects does.
Practice exercises
- Run the example and try to write
acc.balance = 1000000;inmain. Read the error. - Add a function
getTransactionCountthat returns how many deposits and withdrawals succeeded. - Think of a program you use (a music player, a shop): list three classes it might have and their data.