Show contents
Chapter 4 of 7 · 20 min
Creating your own classes
By the end of this chapter, you'll be able to
- Define a class with private attributes and public methods
- Write a constructor with an initialiser list
- Mark as const the methods that don't change the object
- Explain why encapsulation protects a program's rules
A class, some objects
A class is a blueprint: it describes the data (the attributes) and the actions (the methods) of a type of object. An object is an instance built from that blueprint.
#include <iostream>
#include <string>
class Account {
public:
Account(const std::string& owner, double initial_deposit)
: owner_(owner), balance_(initial_deposit) {}
void deposit(double amount) {
if (amount > 0) {
balance_ += amount;
}
}
bool withdraw(double amount) {
if (amount <= 0 || amount > balance_) {
return false; // refused: the rule is protected
}
balance_ -= amount;
return true;
}
double balance() const { return balance_; }
const std::string& owner() const { return owner_; }
private:
std::string owner_;
double balance_;
};
int main() {
Account account("Inès", 100);
account.deposit(50);
bool ok = account.withdraw(500);
std::cout << std::boolalpha << "Withdraw 500: " << ok << "\n";
account.withdraw(30);
std::cout << account.owner() << ": " << account.balance() << "\n";
return 0;
}
Withdraw 500: false
Inès: 120
Let's break it down:
public:makes the following members accessible from outside the class;private:reserves them for the class's methods. By convention, private attributes are given a trailing_here.- The constructor has the name of the class and no return type. It's called when the object is created (
Account account("Inès", 100);). The initialiser list: owner_(owner), balance_(initial_deposit)gives the attributes their initial value. - You call a method with a dot:
account.deposit(50). Inside the method,balance_refers to the attribute of this object. constafter the parentheses (double balance() const) promises that the method doesn't change the object. The compiler checks it.
We read the balance with the balance() method: the attribute itself stays out of reach.
Text description of the animation
- We create an account and only use it through its methods.
- The constructor initialises the two private attributes.
- deposit checks that the amount is positive, then adds it.
- withdraw refuses: the balance is too low. It doesn't change, and the method returns false.
- A withdrawal of 30 is accepted.
- We read the balance with the balance() method: the attribute itself stays out of reach.
Why hide everything?
This is the principle of encapsulation: the outside only sees what the class chooses to show. The benefits are concrete:
- the rules can't be bypassed: no outside code can write
balance_ = -1000; - you can change the inside without breaking the outside: storing the balance in cents, adding a history… the code that uses
depositandwithdrawdoesn't change; - the program is easier to read: the public methods form the object's "user manual".
A struct in C++ is a class whose members are public by default. It's used for plain bundles of data with no rule to protect, like a point {x, y}.
Your turn
Worked exercise
Worked exercise: the Rectangle class
Write a class Rectangle with two private attributes, width_ and height_. The constructor and a method resize(double w, double h) must refuse negative or zero dimensions, replacing them with 1. Add two const methods: area() and perimeter(). With a 4 × 2.5 rectangle, then resized to -3 × 6, the program must display area 10, perimeter 13 then area 6, perimeter 14.
Hint 1
static double valid(double v) { return v > 0 ? v : 1; } and use it in the constructor and in resize.Hint 2
static means the method belongs to the class, not to a particular object: it has no access to any object's attributes, which suits this calculation function.Show the solution and common mistakes
#include <iostream>
class Rectangle {
public:
Rectangle(double w, double h) : width_(valid(w)), height_(valid(h)) {}
void resize(double w, double h) {
width_ = valid(w);
height_ = valid(h);
}
double area() const { return width_ * height_; }
double perimeter() const { return 2 * (width_ + height_); }
private:
static double valid(double v) { return v > 0 ? v : 1; }
double width_;
double height_;
};
int main() {
Rectangle r(4, 2.5);
std::cout << "area " << r.area() << ", perimeter " << r.perimeter() << "\n";
r.resize(-3, 6);
std::cout << "area " << r.area() << ", perimeter " << r.perimeter() << "\n";
return 0;
}
area 10, perimeter 13
area 6, perimeter 14
Common mistakes:
- Only validating in
resize: the constructor would still accept a rectangle with a width of -3. - Making
width_public "to keep it simple": all the protection disappears, and any code can break the rule.
Summary
- 1A class groups attributes and methods; an object is an instance of the class.
- 2private protects the data; public exposes the user manual.
- 3The constructor initialises the object, preferably with an initialiser list.
- 4A const method promises not to change the object.
- 5Encapsulation guarantees that the class's rules are always followed.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.