Classes and OOP · Lesson 14 of 21
struct and class
Data and functions in one type, public and private, and const methods.
A class defines a new type: data (members) and functions that work on it (methods). The only difference between struct and class is that struct members default to public and class members to private. By convention, struct is for plain data and class when there are rules to protect.
#include <iostream>
#include <string>
struct Point {
int x = 0;
int y = 0;
};
class Wallet {
public:
void deposit(int amount) {
if (amount > 0) balance += amount;
}
bool withdraw(int amount) {
if (amount <= 0 || amount > balance) return false;
balance -= amount;
return true;
}
int getBalance() const { return balance; }
private:
int balance = 0; // nobody outside can set this directly
};
int main() {
Point p{3, 4};
std::cout << p.x + p.y << "\n";
Wallet w;
w.deposit(200);
std::cout << w.withdraw(500) << " " << w.withdraw(50) << "\n";
std::cout << w.getBalance() << "\n";
return 0;
}- class Wallet
- public (anyone can call)
- deposit(int)
- withdraw(int)
- getBalance() const
- private (only Wallet's own code)
- int balance
- public (anyone can call)
This is encapsulation: the balance can't go negative, because the only ways to change it check first.
Spot the bug
This program won't compile. Which line?
Complete the code
Complete it so area can be called on a const Rect&.
#include <iostream> struct Rect { int w, h; int area() { return w * h; } }; int main() { const Rect r{3, 5}; std::cout << r.area() << "\n"; }
Exercise
Finish the Timer class: addMinutes(int m) adds minutes, and format() (const) returns text like 2h 05m. The program prints 2h 05m.
Expected output: 2h 05m
#include <iostream>
#include <string>
class Timer {
public:
void addMinutes(int m) {
}
std::string format() const {
return "";
}
private:
int minutes = 0;
};
int main() {
Timer t;
t.addMinutes(95);
t.addMinutes(30);
std::cout << t.format() << "\n";
return 0;
}Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.