You will be able to
- Manage memory safely with RAII and smart pointers
- Write classes with correct copy and move behaviour
- Use templates and the STL fluently
- Apply SOLID and common design patterns
- Build a complete project with exceptions and file storage
Before you start
You should be comfortable with inheritance, virtual functions and operator overloading. This level is about ownership and lifetime: who owns an object, when it is created, copied, moved and destroyed. The live explanations show the heap, pointers and reference counts changing step by step. Compile with -fsanitize=address,undefined while you practise.
Module 1
Pointers, references and the heap
Understand where objects live and how to manage memory by hand before you let smart pointers do it.
Definitions
| Term | Meaning | Example |
|---|---|---|
| Pointer | A variable that stores a memory address | int* p = &x; |
Address-of & | Gives the address of a variable | &x |
Dereference * | Follows a pointer to the value it points at | *p = 20; |
| Reference | Another name (alias) for an existing variable. Cannot be null or reseated | int& r = x; |
nullptr | The "points to nothing" value | int* p = nullptr; |
| Stack | Fast automatic memory for local variables; freed at the end of the block | |
| Heap (free store) | Memory you request with new and must release with delete | |
| Memory leak | Heap memory that is never freed | new without delete |
| Dangling pointer | A pointer to memory that has already been freed | use after delete |
Pointers and references in action
#include <iostream>
using namespace std;
int main() {
int x = 10;
int* p = &x;
int& r = x;
*p = 20;
r++;
cout << x << endl;
cout << (p == &x) << endl;
return 0;
}p holds the address of x. *p = 20 writes through the pointer, so x becomes 20. r is an alias for x, so r++ makes it 21. All three names refer to the same memory, so the output is 21. The comparison p == &x is true, printed as 1.| Pointer | Reference | |
|---|---|---|
| Can be null | Yes | No |
| Can be reassigned | Yes | No, bound once |
| Syntax to use | *p, p->m | Like a normal variable |
| Typical use | Optional or re-pointable objects, heap objects | Function parameters, aliases |
| Stack | Heap | |
|---|---|---|
| Created by | Declaring a local variable | new |
| Freed by | Automatically at end of scope | You, with delete (or a smart pointer) |
| Speed | Very fast | Slower allocation |
| Size | Small (a few MB) | Large, limited by memory |
| Lifetime | Tied to the block | Until you free it |
Step through the life of a heap object and watch what happens to the pointer when you delete it:
#include <iostream>
using namespace std;
class Point {
public:
int x, y;
Point(int a, int b) : x(a), y(b) { cout << "Point created" << endl; }
~Point() { cout << "Point destroyed" << endl; }
};
int main() {
Point* p = new Point(3, 4);
cout << p->x << "," << p->y << endl;
delete p;
int* arr = new int[3]{1, 2, 3};
cout << arr[0] + arr[2] << endl;
delete[] arr;
return 0;
}new Point(3, 4) allocates memory and runs the constructor. delete p runs the destructor and frees the memory. new int[3]{...} allocates an array and must be released with delete[], never plain delete. arr[0] + arr[2] is 1 + 3 = 4.The five classic memory bugs
| Bug | Example | Result | Fix |
|---|---|---|---|
| Leak | new int; never deleted | Memory grows until the program dies | Pair every new with a delete, or use smart pointers |
| Dangling pointer | delete p; *p = 1; | Undefined behaviour | Set to nullptr after delete; do not keep extra raw copies |
| Double delete | delete p; delete p; | Crash | One owner per object |
| Wrong delete | int* a = new int[3]; delete a; | Undefined behaviour | new[] goes with delete[] |
| Uninitialised pointer | int* p; *p = 1; | Writes to a random address | Initialise to nullptr or a valid object |
Key takeaways
&xis an address,*pfollows a pointer, a reference is an alias- Local objects live on the stack and die automatically;
newobjects live on the heap until deleted newpairs withdeleteandnew[]pairs withdelete[]- A pointer left behind after
deleteis dangling; set it tonullptr - Run sanitizers while learning
Practice
Write Point* makePoint(int a, int b) that creates a Point on the heap and returns it. In main, call it, print the x and y, then free it correctly.
Return the result of new Point(a, b). The caller owns the pointer and must delete it.
#include <iostream>
using namespace std;
struct Point { int x, y; };
Point* makePoint(int a, int b) { return new Point{a, b}; }
int main() {
Point* p = makePoint(5, 6);
cout << p->x << " " << p->y << endl;
delete p;
p = nullptr;
return 0;
}Quick quiz
Which statement frees an array created with new int[5]?
Arrays created with new[] must be released with delete[].
What is a dangling pointer?
It still holds the old address but the memory is no longer yours.
Which can be reassigned to refer to another variable?
References are bound once at initialisation.
Module 2
Copy, move and the Rule of Five
Control how objects that own resources are copied and moved.
Definitions
| Term | Meaning |
|---|---|
| Shallow copy | Copies member values including pointer values, so two objects share one resource (dangerous) |
| Deep copy | Allocates a new resource and copies the contents so each object owns its own |
| Copy constructor | T(const T& other) creates a new object as a copy of an existing one |
| Copy assignment | T& operator=(const T&) overwrites an existing object with a copy |
| Move constructor | T(T&& other) noexcept steals the resources of a temporary or finished object |
| Move assignment | T& operator=(T&&) noexcept steals into an existing object |
| lvalue | A named thing you can take the address of: x |
| rvalue | A temporary with no name: x + 1, a function result |
std::move | A cast to rvalue reference. It marks an object as "safe to steal from" |
| Rule of Three / Five | If you need to write one of destructor, copy constructor or copy assignment (Three), you probably need all of them, plus the two move operations (Five) |
| Rule of Zero | Design classes so they need none of the five, by holding members that manage themselves (vector, string, smart pointers) |
The problem: shallow copy
If a class owns memory through a raw pointer and you let the compiler copy it, both objects point to one block. Both destructors free it, so it is freed twice. Step through the bug and its fix:
The solution for speed: move
Copying a large buffer just to throw away the original is wasteful. A move transfers ownership of the existing buffer in constant time:
All five special functions together
This class prints a message from each function so you can see which one C++ chooses.
#include <iostream>
#include <algorithm>
#include <utility>
using namespace std;
class Buffer {
int* d;
size_t n;
public:
Buffer(size_t n) : d(new int[n]()), n(n) { cout << "construct" << endl; }
~Buffer() { delete[] d; cout << "destroy" << endl; }
Buffer(const Buffer& o) : d(new int[o.n]), n(o.n) {
copy(o.d, o.d + n, d);
cout << "copy" << endl;
}
Buffer(Buffer&& o) noexcept : d(o.d), n(o.n) {
o.d = nullptr; o.n = 0;
cout << "move" << endl;
}
Buffer& operator=(Buffer o) {
swap(d, o.d); swap(n, o.n);
return *this;
}
};
int main() {
Buffer a(3);
Buffer b = a;
Buffer c = move(a);
return 0;
}Buffer a(3) calls the normal constructor. Buffer b = a copies because a is a named lvalue, so the copy constructor allocates a new array. move(a) casts a to an rvalue, so the move constructor steals its pointer and leaves a empty. At the end three objects are destroyed. Copy assignment here uses the copy-and-swap idiom: it takes its argument by value (so a copy or a move constructs it) and swaps, which also makes it exception-safe and handles self-assignment.| Style | What you write | When |
|---|---|---|
| Rule of Zero | Nothing. Use vector, string, unique_ptr members | Default choice. Always try this first |
| Rule of Three | Destructor, copy constructor, copy assignment | Pre-C++11 code owning raw resources |
| Rule of Five | The three plus move constructor and move assignment | A class that really manages a resource and must be fast to move |
= default / = delete | T(const T&) = delete; | Explicitly keep or forbid an operation, for example a non-copyable class |
Key takeaways
- Raw owning pointers need a deep copy, otherwise the default copy shares the block
- Copy duplicates, move transfers ownership in constant time
std::moveonly casts; the move constructor does the work- Prefer the Rule of Zero; if you write one special function, consider all five
- Mark move operations
noexcept
Practice
Write an Array class with a private int* and size. Provide a constructor, destructor, deep-copy constructor, move constructor, copy-and-swap assignment, set(i, v) and get(i). Show that after Array b = a; b.set(0, 99); the original is unchanged, then move b into c.
Model it on Buffer. A deep copy allocates new int[o.n] and uses std::copy. The move constructor steals the pointer and sets the source pointer to nullptr.
#include <iostream>
#include <algorithm>
#include <utility>
using namespace std;
class Array {
int* d;
size_t n;
public:
Array(size_t n) : d(new int[n]()), n(n) {}
~Array() { delete[] d; }
Array(const Array& o) : d(new int[o.n]), n(o.n) { copy(o.d, o.d + n, d); }
Array(Array&& o) noexcept : d(o.d), n(o.n) { o.d = nullptr; o.n = 0; }
Array& operator=(Array o) { swap(d, o.d); swap(n, o.n); return *this; }
void set(size_t i, int v) { d[i] = v; }
int get(size_t i) const { return d[i]; }
};
int main() {
Array a(3);
a.set(0, 1);
Array b = a;
b.set(0, 99);
cout << a.get(0) << " " << b.get(0) << endl;
Array c = move(b);
cout << c.get(0) << endl;
return 0;
}Quick quiz
A class owns memory through a raw pointer. What happens if you rely on the default copy?
The default copy is shallow: it copies the pointer, not the block.
What does std::move(x) actually do?
It is just a cast. The move constructor or assignment performs the transfer.
Which approach is recommended whenever possible?
Let standard types manage resources so you write none of the special functions.
Module 3
RAII and smart pointers
Let destructors manage resources so leaks become impossible by design.
Definitions
| Term | Meaning |
|---|---|
| RAII | Resource Acquisition Is Initialisation: a resource (memory, file, lock) is acquired in a constructor and released in the destructor, so its lifetime is tied to an object |
| Smart pointer | A class that wraps a raw pointer and deletes it automatically |
unique_ptr | Sole ownership. Cannot be copied, only moved. Zero overhead |
shared_ptr | Shared ownership with a reference count. The last owner deletes the object |
weak_ptr | A non-owning observer of a shared_ptr that does not keep the object alive |
make_unique / make_shared | Safe factory functions that create the object and the smart pointer together |
| Ownership | The responsibility for deleting an object. Every heap object must have exactly one owner (or a shared one) |
RAII with exceptions
Manual delete is skipped when a function exits early or throws. A destructor always runs. Step through a function that throws an exception and watch the resource get released anyway:
unique_ptr: one owner
#include <iostream>
#include <memory>
using namespace std;
class Res {
public:
Res() { cout << "acquire" << endl; }
~Res() { cout << "release" << endl; }
};
int main() {
unique_ptr<Res> a = make_unique<Res>();
unique_ptr<Res> b = move(a);
cout << (a == nullptr) << endl;
return 0;
}make_unique creates the Res (message "acquire"). A unique_ptr cannot be copied because that would give two owners, so b = a is a compile error. move(a) transfers ownership to b and a becomes null, which is why a == nullptr prints 1. When main ends, b is destroyed and the Res is released exactly once.shared_ptr: shared ownership
Use it when several parts of the program must keep an object alive and none of them is the obvious owner.
#include <iostream>
#include <memory>
using namespace std;
class Res {
public:
Res() { cout << "acquire" << endl; }
~Res() { cout << "release" << endl; }
};
int main() {
auto a = make_shared<Res>();
cout << a.use_count() << endl;
{
auto b = a;
cout << a.use_count() << endl;
}
cout << a.use_count() << endl;
return 0;
}use_count() shows how many owners exist: 1, then 2 while b lives, then 1 again. The "release" message appears last, only when a is destroyed and the count reaches 0.weak_ptr: observe without owning
Two objects that hold shared_ptr to each other (a parent and child, say) keep each other alive forever: a cycle leak. Make the back-link a weak_ptr.
#include <iostream>
#include <memory>
using namespace std;
int main() {
shared_ptr<int> s = make_shared<int>(42);
weak_ptr<int> w = s;
cout << w.use_count() << endl;
if (auto p = w.lock()) cout << *p << endl;
s.reset();
cout << w.expired() << endl;
return 0;
}weak_ptr does not increase the count, so use_count() stays 1. lock() returns a shared_ptr if the object is still alive (here it prints 42) or an empty one if not. After s.reset() the object is gone and expired() is true (1).| Need | Use |
|---|---|
| One clear owner | unique_ptr (the default choice) |
| Several owners, lifetime shared | shared_ptr |
| Back-pointer or cache that must not keep an object alive | weak_ptr |
| Just using an object owned elsewhere | A plain reference or raw pointer (non-owning) |
| Polymorphic collection | vector<unique_ptr<Base>> |
Key takeaways
- RAII ties a resource to an object: constructor acquires, destructor releases
unique_ptris the default owner and is move-onlyshared_ptrcounts owners; the last one deletesweak_ptrbreaks ownership cycles- Prefer
make_uniqueandmake_sharedovernew
Practice
Rewrite this raw-pointer code with smart pointers so that it cannot leak: Shape* s = new Circle(2); useShape(s); delete s; where useShape takes a const Shape&.
Create with make_unique<Circle>(2) and pass *s to the function. No delete is needed.
#include <iostream>
#include <memory>
using namespace std;
class Shape {
public:
virtual double area() const = 0;
virtual ~Shape() = default;
};
class Circle : public Shape {
double r;
public:
Circle(double r) : r(r) {}
double area() const override { return 3.14 * r * r; }
};
void useShape(const Shape& s) { cout << s.area() << endl; }
int main() {
unique_ptr<Shape> s = make_unique<Circle>(2);
useShape(*s);
return 0;
}Quick quiz
Why can a unique_ptr not be copied?
Unique ownership means exactly one owner at a time, so you can only move it.
What problem does weak_ptr solve?
A weak back-reference does not keep the object alive, so cycles can be freed.
What does RAII guarantee when an exception is thrown?
Stack unwinding runs destructors of all local objects.
Module 4
Templates and the STL
Write code once for any type and use the standard containers and algorithms.
Definitions
| Term | Meaning |
|---|---|
| Template | A blueprint for functions or classes that works with any type: template <typename T> |
| Instantiation | The compiler generating a real function or class from a template for specific types |
| Template argument deduction | The compiler working out T from the call: biggest(3, 7) gives T = int |
| Generic programming | Writing algorithms that depend on what a type can do rather than what it is |
| STL | The Standard Template Library: containers, iterators and algorithms |
| Container | An object that stores other objects: vector, map… |
| Iterator | A pointer-like object that walks through a container |
| Lambda | An inline unnamed function: [](int x) { return x > 3; } |
Function templates
Step through how one recipe becomes two real functions:
Class templates
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <typename T>
class Stack {
vector<T> items;
public:
void push(const T& x) { items.push_back(x); }
T pop() {
T top = items.back();
items.pop_back();
return top;
}
bool empty() const { return items.empty(); }
};
int main() {
Stack<int> s;
s.push(1); s.push(2); s.push(3);
while (!s.empty()) cout << s.pop() << " ";
cout << endl;
Stack<string> w;
w.push("A"); w.push("B");
cout << w.pop() << endl;
return 0;
}Stack<T> is a recipe for a whole class. Stack<int> and Stack<string> are two separate real classes made from it. A stack is last-in first-out, so 3 comes out first. Because the class stores items in a vector<T>, memory is managed for you (Rule of Zero).The STL containers
| Container | Description | Typical use | Lookup |
|---|---|---|---|
vector<T> | Growable array | Default choice for a list | Index O(1) |
array<T,N> | Fixed-size array | Size known at compile time | Index O(1) |
list<T> | Doubly linked list | Frequent inserts in the middle | No index |
deque<T> | Double-ended queue | Push/pop both ends | Index O(1) |
set<T> | Sorted unique values | Membership tests, sorted output | O(log n) |
map<K,V> | Sorted key to value | Dictionaries sorted by key | O(log n) |
unordered_map<K,V> | Hash table | Fast key lookup, no order | O(1) average |
Algorithms, iterators and lambdas
Algorithms such as sort, find and count_if work on any container through iterators, so you rarely write loops by hand.
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {5, 2, 9, 1};
sort(v.begin(), v.end());
for (int x : v) cout << x << " ";
cout << endl;
int big = count_if(v.begin(), v.end(), [](int x) { return x > 3; });
cout << big << endl;
map<string, int> age;
age["Ravi"] = 22;
age["Asha"] = 20;
for (const auto& [name, a] : age) cout << name << "=" << a << endl;
return 0;
}v.begin() and v.end() are iterators marking the range. sort puts the values in order. The lambda [](int x) { return x > 3; } is an unnamed function passed to count_if, which counts 5 and 9, so it prints 2. A map keeps keys sorted, so Asha comes before Ravi regardless of insertion order. The [name, a] form is a C++17 structured binding and needs -std=c++17.Key takeaways
template <typename T>defines a recipe; the compiler stamps out real code per type- Class templates are used as
Stack<int> - Prefer
vector; usemaporunordered_mapfor key lookup - Algorithms plus lambdas replace most hand-written loops
- Keep template code in headers
Practice
Write a class template Pair<K, V> that stores a key and a value and has a show() method printing them. Create Pair<string, int>("Asha", 20) and show it.
Declare template <typename K, typename V> and two members. The constructor takes const K& and const V&.
#include <iostream>
#include <string>
using namespace std;
template <typename K, typename V>
class Pair {
K key;
V value;
public:
Pair(const K& k, const V& v) : key(k), value(v) {}
void show() const { cout << key << " " << value << endl; }
};
int main() {
Pair<string, int> p("Asha", 20);
p.show();
return 0;
}Quick quiz
When is a template instantiated?
The compiler generates code for each distinct set of template arguments it sees.
Which container gives fast lookup by key with no ordering?
unordered_map is a hash table with O(1) average lookup.
Why do template definitions normally go in header files?
Without the body visible, the compiler cannot create the instantiation.
Module 5
Design patterns and SOLID
Structure bigger programs so they stay easy to change.
Definitions
| Term | Meaning |
|---|---|
| Design principle | A general guideline for good structure |
| SOLID | Five principles for class design: Single responsibility, Open/closed, Liskov substitution, Interface segregation, Dependency inversion |
| Design pattern | A named, reusable solution to a common design problem |
| Coupling | How much one class depends on the details of another. Aim low |
| Cohesion | How closely the parts of one class belong together. Aim high |
The five SOLID principles
| Principle | Meaning | Violation | Fix |
|---|---|---|---|
| Single Responsibility | A class has one reason to change | Report calculates, prints and saves to disk | Split into Report, Printer, Storage |
| Open/Closed | Open to extension, closed to modification | Adding a shape means editing a big if chain | Add a new subclass of Shape |
| Liskov Substitution | A derived object must work wherever the base is expected | Square derived from Rectangle breaks width/height rules | Do not inherit when behaviour differs; use composition |
| Interface Segregation | Many small interfaces beat one fat one | A Machine interface with print, scan and fax forced on a simple printer | Split into Printer, Scanner |
| Dependency Inversion | Depend on abstractions, not concrete classes | Cart creates a CardPayment itself | Pass a Payment& into Cart |
Strategy pattern: swap behaviour
Define a family of algorithms behind an interface and pass the one you want. It applies Open/Closed and Dependency Inversion together.
#include <iostream>
using namespace std;
class Discount {
public:
virtual double apply(double price) const = 0;
virtual ~Discount() = default;
};
class NoDiscount : public Discount {
public:
double apply(double p) const override { return p; }
};
class Festival : public Discount {
public:
double apply(double p) const override { return p * 0.8; }
};
class Cart {
const Discount& rule;
public:
Cart(const Discount& d) : rule(d) {}
double total(double price) const { return rule.apply(price); }
};
int main() {
NoDiscount none;
Festival sale;
Cart a(none), b(sale);
cout << a.total(1000) << endl;
cout << b.total(1000) << endl;
return 0;
}Cart does not know which discount it uses; it depends on the Discount interface (Dependency Inversion). To add a student discount you write a new class and change nothing else (Open/Closed). The cart holds a reference to the rule it was given.Factory pattern: create objects without naming the class
#include <iostream>
#include <memory>
#include <string>
using namespace std;
class Shape {
public:
virtual string name() const = 0;
virtual ~Shape() = default;
};
class Circle : public Shape {
public:
string name() const override { return "Circle"; }
};
class Square : public Shape {
public:
string name() const override { return "Square"; }
};
unique_ptr<Shape> make(const string& kind) {
if (kind == "circle") return make_unique<Circle>();
if (kind == "square") return make_unique<Square>();
return nullptr;
}
int main() {
for (string k : {"circle", "square", "hexagon"}) {
auto s = make(k);
cout << (s ? s->name() : "unknown") << endl;
}
return 0;
}unique_ptr<Shape>. They never write new Circle, so adding a new shape only changes the factory. An unknown kind returns an empty pointer, which the caller tests with (s ? ... : ...).Singleton pattern: exactly one instance
#include <iostream>
#include <string>
using namespace std;
class Logger {
Logger() { cout << "Logger created" << endl; }
public:
static Logger& get() {
static Logger instance;
return instance;
}
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
void log(const string& m) { cout << "[LOG] " << m << endl; }
};
int main() {
Logger::get().log("start");
Logger::get().log("end");
return 0;
}static object is created the first time get() runs (thread-safe since C++11) and reused afterwards, which is why "Logger created" prints once. Copying is deleted so no second instance can sneak in.| Pattern | Intent | Typical C++ ingredients |
|---|---|---|
| Strategy | Swap algorithms at run time | Interface + reference or unique_ptr member |
| Factory | Create objects without naming concrete classes | Function returning unique_ptr<Base> |
| Singleton | One global instance | Private constructor + static accessor |
| Observer | Notify many objects when one changes | Subject keeps a vector of observer pointers or std::function |
| Decorator | Add behaviour by wrapping an object | Wrapper holding a base reference and implementing the same interface |
| RAII | Tie resource lifetime to an object | Constructors and destructors |
Key takeaways
- SOLID: single responsibility, open/closed, Liskov, interface segregation, dependency inversion
- Depend on interfaces; inject dependencies through constructors
- Strategy swaps behaviour, Factory hides construction, Singleton limits to one instance
- Low coupling and high cohesion make code easy to change
Practice
Use the Strategy pattern for shipping cost. Create an interface Shipping with double cost(double weight) const. Implement Standard (weight * 10) and Express (weight * 25). Print the cost of a 2 kg parcel for each.
Follow the Discount example: an interface, two overrides, and a function or class that takes a const Shipping&.
#include <iostream>
using namespace std;
class Shipping {
public:
virtual double cost(double w) const = 0;
virtual ~Shipping() = default;
};
class Standard : public Shipping {
public:
double cost(double w) const override { return w * 10; }
};
class Express : public Shipping {
public:
double cost(double w) const override { return w * 25; }
};
void quote(const Shipping& s) { cout << s.cost(2) << endl; }
int main() {
Standard a; Express b;
quote(a);
quote(b);
return 0;
}Quick quiz
Which SOLID principle says "depend on abstractions, not concrete classes"?
High-level code should depend on interfaces and receive concrete objects from outside.
Which pattern lets you swap algorithms at run time?
Strategy puts each algorithm behind a common interface.
What does the Single Responsibility Principle say?
Mixing calculation, printing and storage in one class makes every change risky.
Module 6
Exceptions and the capstone project
Handle errors safely and put everything together in a real project.
Definitions
| Term | Meaning |
|---|---|
| Exception | An object thrown to signal that something went wrong, which interrupts normal flow |
throw | Raises an exception |
try / catch | try guards code; catch handles a matching exception type |
| Stack unwinding | Leaving functions one by one while destroying their locals until a handler is found |
std::exception | Base class of standard exceptions with a virtual what() message |
noexcept | Promises a function will not throw |
| Exception safety | Basic: no leaks and valid state. Strong: operation either completes or changes nothing. No-throw: never fails |
Use exceptions for exceptional situations (bad input, failed resource, broken rule), not for ordinary control flow. Because of RAII (module 3), cleanup is automatic when an exception passes through.
#include <iostream>
#include <stdexcept>
using namespace std;
class InsufficientFunds : public runtime_error {
public:
InsufficientFunds() : runtime_error("Insufficient funds") {}
};
class Account {
double balance;
public:
Account(double b) : balance(b) {}
void withdraw(double amt) {
if (amt > balance) throw InsufficientFunds();
balance -= amt;
}
double get() const { return balance; }
};
int main() {
Account acc(100);
try {
acc.withdraw(30);
acc.withdraw(500);
cout << "not reached" << endl;
} catch (const exception& e) {
cout << "Error: " << e.what() << endl;
}
cout << acc.get() << endl;
return 0;
}InsufficientFunds derives from runtime_error, so it carries a message and can be caught as a std::exception. The first withdrawal succeeds (balance 70). The second throws, so the line after it is skipped and control jumps to the matching catch. Always catch by const reference to avoid slicing and copies. The program then continues and prints 70.| Guideline | Why |
|---|---|
Throw by value, catch by const& | Avoids slicing and copies |
Derive custom exceptions from std::exception types | Callers can catch generically |
| Order catch blocks from most specific to most general | The first matching handler wins |
| Never throw from a destructor | It can terminate the program during unwinding |
| Use RAII, not manual cleanup, in code that can throw | Destructors run during unwinding |
Capstone project: Library Management System
This project uses everything in the course. Build it in the order below and run the code at every stage.
| Requirement | Concepts used |
|---|---|
Items (Book, Magazine, DVD) share an interface with virtual double lateFee(int days) const = 0 | Abstract classes, polymorphism, inheritance |
The library owns items through vector<unique_ptr<Item>> | Smart pointers, RAII, STL |
| Members borrow and return items; limit 3 items per member | Encapsulation, composition |
Borrowing an unavailable item throws ItemUnavailable | Exceptions |
| Find items by title using algorithms and lambdas | STL algorithms |
Print members and items with operator<< | Operator overloading |
| Save and load all data from a text file | File I/O with RAII streams |
Skeleton to start from
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
class ItemUnavailable : public runtime_error {
public:
ItemUnavailable(const string& t) : runtime_error(t + " is not available") {}
};
class Item {
protected:
int id;
string title;
bool available = true;
public:
Item(int id, string title) : id(id), title(move(title)) {}
virtual ~Item() = default;
virtual double lateFee(int days) const = 0;
virtual string kind() const = 0;
const string& getTitle() const { return title; }
bool isAvailable() const { return available; }
void borrow() { if (!available) throw ItemUnavailable(title); available = false; }
void giveBack() { available = true; }
};
class Book : public Item {
public:
using Item::Item;
double lateFee(int days) const override { return days * 2.0; }
string kind() const override { return "Book"; }
};
class Library {
vector<unique_ptr<Item>> items;
public:
void add(unique_ptr<Item> it) { items.push_back(move(it)); }
Item* find(const string& title); // TODO: use find_if with a lambda
void save(const string& file) const; // TODO: use std::ofstream
void load(const string& file); // TODO: use std::ifstream
};
int main() {
Library lib;
lib.add(make_unique<Book>(1, "C++ Primer"));
// TODO: add Member, borrowing, fees and menu
return 0;
}using Item::Item; inherits the base constructors. Items are moved into the library, so it is the single owner. Replace each TODO one at a time and run after each change.| Milestone | Goal |
|---|---|
| 1 | Items and the Library compile and print the catalogue |
| 2 | Member class, borrow and return with the 3-item limit |
| 3 | Exceptions for unavailable items and limit exceeded |
| 4 | Fees through polymorphism, search with find_if |
| 5 | Save and load from a file, then a text menu in main |
Key takeaways
- Throw by value and catch by const reference
- Custom exceptions derive from
std::exceptiontypes - RAII keeps cleanup correct while exceptions propagate
- The capstone combines abstract classes, polymorphism, smart pointers, STL, exceptions and operator overloading
Practice
Write double safeDivide(double a, double b) that throws invalid_argument("Cannot divide by zero") when b is 0. In main, catch it and print the message, then print safeDivide(10, 2).
Include <stdexcept> and catch const invalid_argument&.
#include <iostream>
#include <stdexcept>
using namespace std;
double safeDivide(double a, double b) {
if (b == 0) throw invalid_argument("Cannot divide by zero");
return a / b;
}
int main() {
try {
safeDivide(1, 0);
} catch (const invalid_argument& e) {
cout << e.what() << endl;
}
cout << safeDivide(10, 2) << endl;
return 0;
}Quick quiz
How should you catch an exception?
Catching by const reference avoids slicing and unnecessary copies.
What happens to local objects when an exception leaves a function?
Destructors of locals run as the stack unwinds, which is why RAII works.
Which should NEVER throw an exception?
Throwing from a destructor during unwinding can terminate the program.
REVISION · ADVANCED
Definition bank, interview questions and drills
These are the questions most asked in C++ interviews. Answer in two or three sentences, then offer a tiny example.
Advanced C++ OOP definitions
- Pointer
- A variable holding a memory address.
- Reference
- An alias for an existing variable.
- Heap / free store
- Memory allocated with
newand freed withdelete. - Memory leak
- Heap memory that is never released.
- Dangling pointer
- A pointer to memory that has already been freed.
- Shallow copy
- A copy that duplicates pointer values so two objects share one resource.
- Deep copy
- A copy that duplicates the pointed-to resource.
- Copy constructor
- Creates an object as a copy of another of the same type.
- Move constructor
- Transfers resources from a temporary or moved-from object.
- Rvalue reference
T&&, a reference that binds to temporaries and enables moving.- Rule of Three / Five / Zero
- Guidelines about which special member functions to write together; Zero means write none.
- RAII
- Binding a resource's lifetime to an object through its constructor and destructor.
- unique_ptr
- A smart pointer with sole ownership, move-only.
- shared_ptr
- A smart pointer with reference-counted shared ownership.
- weak_ptr
- A non-owning observer of a shared_ptr that avoids cycles.
- Template
- A blueprint from which the compiler generates functions or classes for given types.
- STL
- Standard containers, iterators and algorithms.
- Lambda
- An inline anonymous function object.
- SOLID
- Five object-oriented design principles.
- Stack unwinding
- Destroying locals while an exception travels to a handler.
- noexcept
- Specifies that a function does not throw.
Interview-style questions with answers
Q1. What is the Rule of Five?
Answer: If a class needs a custom destructor, copy constructor or copy assignment, it usually needs all five of: destructor, copy constructor, copy assignment, move constructor and move assignment.
Q2. Explain shallow and deep copy.
Answer: A shallow copy copies pointer values, so objects share one resource and may free it twice. A deep copy allocates a new resource and copies the contents so each object owns its own.
Q3. unique_ptr versus shared_ptr?
Answer: unique_ptr has one owner, cannot be copied and has no overhead. shared_ptr has reference-counted shared ownership and deletes the object when the last owner goes.
Q4. What is RAII and why is it important?
Answer: Acquire a resource in a constructor and release it in the destructor. Cleanup is then automatic, even with early returns or exceptions, which removes leaks.
Q5. What does std::move do?
Answer: It casts an object to an rvalue reference so a move constructor or move assignment can be selected. It does not move anything itself.
Q6. What is a vtable?
Answer: A table of virtual function pointers per class. Each object of a polymorphic class has a hidden pointer (vptr) to its class's vtable, used for run-time dispatch.
Q7. Why must a polymorphic base class have a virtual destructor?
Answer: Deleting a derived object through a base pointer without it is undefined behaviour and skips the derived destructor.
Q8. How do templates differ from inheritance-based polymorphism?
Answer: Templates give compile-time polymorphism: separate code is generated per type with no run-time cost. Inheritance with virtual functions chooses behaviour at run time through the vtable.
Spot the bug
Will this compile? unique_ptr<int> a = make_unique<int>(5);
unique_ptr<int> b = a;
Answer: No. The copy constructor of unique_ptr is deleted. Use unique_ptr<int> b = std::move(a);.
What is wrong here? int* p = new int[3];
delete p;
Answer: Undefined behaviour. Memory from new[] must be released with delete[].
What is printed? string s = "hi";
string t = std::move(s);
cout << t;
Answer: hi. After the move, s is valid but unspecified (usually empty), so do not use its value.
Practical assignments
- Write a
Stringclass with deep copy and move, and test it under-fsanitize=address. - Convert an old raw-pointer program to
unique_ptrandshared_ptr. - Create a generic
Matrix<T>template withoperator+andoperator<<. - Implement Observer with
std::functioncallbacks. - Finish the Library Management System capstone.
Course complete
Finish the capstone, then revisit the roadmap and pick a new challenge.
Back to roadmap