Lesson content
Read, practise, then check your understanding
A class is a blueprint that groups related data and functions. An object is a concrete instance of that class. Together they let you model a concept while protecting its rules.
Define a small class
#include <iostream>
#include <string>
class BankAccount {
private:
std::string owner;
double balance;
public:
BankAccount(std::string name, double openingBalance)
: owner(name), balance(openingBalance) {}
void deposit(double amount) {
if (amount > 0) balance += amount;
}
double getBalance() const {
return balance;
}
};
owner and balance are private, so callers cannot place the object in an invalid state directly. The public functions form the class interface.
Construct and use objects
BankAccount savings("Mira", 1000.0);
savings.deposit(250.0);
std::cout << savings.getBalance(); // 1250
The constructor has the same name as the class and initializes a new object. The initializer list after : constructs data members efficiently.
Keep responsibilities focused
A good class represents one clear idea. It should protect its own invariants—the facts that must always remain true. For BankAccount, one invariant might be that deposits must be positive.
Use const on a member function that does not change object state. This communicates intent and lets the function run on const objects.
Value or reference?
Passing a large object by value creates a copy. A const reference avoids that copy and prevents accidental modification.
void printAccount(const BankAccount& account) {
std::cout << account.getBalance();
}
Quick checklist
- Keep data private by default.
- Expose small operations that preserve the object’s rules.
- Initialize members in a constructor initializer list.
- Mark read-only member functions
const.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.