CIPHERCODE.AI · C++ OOP ADVANCED

C++ OOP advanced

Own your memory, move instead of copy, write generic code, and design systems that survive change.

  • 6 modules
  • 5 live explanations
  • Capstone project

    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.

    About 3 hours

    Definitions

    TermMeaningExample
    PointerA variable that stores a memory addressint* p = &x;
    Address-of &Gives the address of a variable&x
    Dereference *Follows a pointer to the value it points at*p = 20;
    ReferenceAnother name (alias) for an existing variable. Cannot be null or reseatedint& r = x;
    nullptrThe "points to nothing" valueint* p = nullptr;
    StackFast 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 leakHeap memory that is never freednew without delete
    Dangling pointerA pointer to memory that has already been freeduse after delete

    Pointers and references in action

    pointers.cpp
    #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.
    PointerReference
    Can be nullYesNo
    Can be reassignedYesNo, bound once
    Syntax to use*p, p->mLike a normal variable
    Typical useOptional or re-pointable objects, heap objectsFunction parameters, aliases
    StackHeap
    Created byDeclaring a local variablenew
    Freed byAutomatically at end of scopeYou, with delete (or a smart pointer)
    SpeedVery fastSlower allocation
    SizeSmall (a few MB)Large, limited by memory
    LifetimeTied to the blockUntil you free it

    Step through the life of a heap object and watch what happens to the pointer when you delete it:

    heap.cpp
    #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

    BugExampleResultFix
    Leaknew int; never deletedMemory grows until the program diesPair every new with a delete, or use smart pointers
    Dangling pointerdelete p; *p = 1;Undefined behaviourSet to nullptr after delete; do not keep extra raw copies
    Double deletedelete p; delete p;CrashOne owner per object
    Wrong deleteint* a = new int[3]; delete a;Undefined behaviournew[] goes with delete[]
    Uninitialised pointerint* p; *p = 1;Writes to a random addressInitialise to nullptr or a valid object

    Key takeaways

    • &x is an address, *p follows a pointer, a reference is an alias
    • Local objects live on the stack and die automatically; new objects live on the heap until deleted
    • new pairs with delete and new[] pairs with delete[]
    • A pointer left behind after delete is dangling; set it to nullptr
    • 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.

    make.cpp
    #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]?

    What is a dangling pointer?

    Which can be reassigned to refer to another variable?

    Module 2

    Copy, move and the Rule of Five

    Control how objects that own resources are copied and moved.

    About 3.5 hours

    Definitions

    TermMeaning
    Shallow copyCopies member values including pointer values, so two objects share one resource (dangerous)
    Deep copyAllocates a new resource and copies the contents so each object owns its own
    Copy constructorT(const T& other) creates a new object as a copy of an existing one
    Copy assignmentT& operator=(const T&) overwrites an existing object with a copy
    Move constructorT(T&& other) noexcept steals the resources of a temporary or finished object
    Move assignmentT& operator=(T&&) noexcept steals into an existing object
    lvalueA named thing you can take the address of: x
    rvalueA temporary with no name: x + 1, a function result
    std::moveA cast to rvalue reference. It marks an object as "safe to steal from"
    Rule of Three / FiveIf 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 ZeroDesign 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.

    buffer.cpp
    #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.
    StyleWhat you writeWhen
    Rule of ZeroNothing. Use vector, string, unique_ptr membersDefault choice. Always try this first
    Rule of ThreeDestructor, copy constructor, copy assignmentPre-C++11 code owning raw resources
    Rule of FiveThe three plus move constructor and move assignmentA class that really manages a resource and must be fast to move
    = default / = deleteT(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::move only 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.

    array.cpp
    #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?

    What does std::move(x) actually do?

    Which approach is recommended whenever possible?

    Module 3

    RAII and smart pointers

    Let destructors manage resources so leaks become impossible by design.

    About 3 hours

    Definitions

    TermMeaning
    RAIIResource 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 pointerA class that wraps a raw pointer and deletes it automatically
    unique_ptrSole ownership. Cannot be copied, only moved. Zero overhead
    shared_ptrShared ownership with a reference count. The last owner deletes the object
    weak_ptrA non-owning observer of a shared_ptr that does not keep the object alive
    make_unique / make_sharedSafe factory functions that create the object and the smart pointer together
    OwnershipThe 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

    unique.cpp
    #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.

    shared.cpp
    #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.

    weak.cpp
    #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;
    }
    A 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).
    NeedUse
    One clear ownerunique_ptr (the default choice)
    Several owners, lifetime sharedshared_ptr
    Back-pointer or cache that must not keep an object aliveweak_ptr
    Just using an object owned elsewhereA plain reference or raw pointer (non-owning)
    Polymorphic collectionvector<unique_ptr<Base>>

    Key takeaways

    • RAII ties a resource to an object: constructor acquires, destructor releases
    • unique_ptr is the default owner and is move-only
    • shared_ptr counts owners; the last one deletes
    • weak_ptr breaks ownership cycles
    • Prefer make_unique and make_shared over new

    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.

    smart.cpp
    #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?

    What problem does weak_ptr solve?

    What does RAII guarantee when an exception is thrown?

    Module 4

    Templates and the STL

    Write code once for any type and use the standard containers and algorithms.

    About 4 hours

    Definitions

    TermMeaning
    TemplateA blueprint for functions or classes that works with any type: template <typename T>
    InstantiationThe compiler generating a real function or class from a template for specific types
    Template argument deductionThe compiler working out T from the call: biggest(3, 7) gives T = int
    Generic programmingWriting algorithms that depend on what a type can do rather than what it is
    STLThe Standard Template Library: containers, iterators and algorithms
    ContainerAn object that stores other objects: vector, map…
    IteratorA pointer-like object that walks through a container
    LambdaAn inline unnamed function: [](int x) { return x > 3; }

    Function templates

    Step through how one recipe becomes two real functions:

    Class templates

    stack.cpp
    #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

    ContainerDescriptionTypical useLookup
    vector<T>Growable arrayDefault choice for a listIndex O(1)
    array<T,N>Fixed-size arraySize known at compile timeIndex O(1)
    list<T>Doubly linked listFrequent inserts in the middleNo index
    deque<T>Double-ended queuePush/pop both endsIndex O(1)
    set<T>Sorted unique valuesMembership tests, sorted outputO(log n)
    map<K,V>Sorted key to valueDictionaries sorted by keyO(log n)
    unordered_map<K,V>Hash tableFast key lookup, no orderO(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.

    stl.cpp
    #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; use map or unordered_map for 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&.

    pair.cpp
    #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?

    Which container gives fast lookup by key with no ordering?

    Why do template definitions normally go in header files?

    Module 5

    Design patterns and SOLID

    Structure bigger programs so they stay easy to change.

    About 4 hours

    Definitions

    TermMeaning
    Design principleA general guideline for good structure
    SOLIDFive principles for class design: Single responsibility, Open/closed, Liskov substitution, Interface segregation, Dependency inversion
    Design patternA named, reusable solution to a common design problem
    CouplingHow much one class depends on the details of another. Aim low
    CohesionHow closely the parts of one class belong together. Aim high

    The five SOLID principles

    PrincipleMeaningViolationFix
    Single ResponsibilityA class has one reason to changeReport calculates, prints and saves to diskSplit into Report, Printer, Storage
    Open/ClosedOpen to extension, closed to modificationAdding a shape means editing a big if chainAdd a new subclass of Shape
    Liskov SubstitutionA derived object must work wherever the base is expectedSquare derived from Rectangle breaks width/height rulesDo not inherit when behaviour differs; use composition
    Interface SegregationMany small interfaces beat one fat oneA Machine interface with print, scan and fax forced on a simple printerSplit into Printer, Scanner
    Dependency InversionDepend on abstractions, not concrete classesCart creates a CardPayment itselfPass 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.

    strategy.cpp
    #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

    factory.cpp
    #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;
    }
    Callers ask for a shape by name and receive a 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

    singleton.cpp
    #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;
    }
    The constructor is private, so nobody else can create a Logger. The function-local 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.
    PatternIntentTypical C++ ingredients
    StrategySwap algorithms at run timeInterface + reference or unique_ptr member
    FactoryCreate objects without naming concrete classesFunction returning unique_ptr<Base>
    SingletonOne global instancePrivate constructor + static accessor
    ObserverNotify many objects when one changesSubject keeps a vector of observer pointers or std::function
    DecoratorAdd behaviour by wrapping an objectWrapper holding a base reference and implementing the same interface
    RAIITie resource lifetime to an objectConstructors 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&.

    ship.cpp
    #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"?

    Which pattern lets you swap algorithms at run time?

    What does the Single Responsibility Principle say?

    Module 6

    Exceptions and the capstone project

    Handle errors safely and put everything together in a real project.

    About 6 hours including the capstone

    Definitions

    TermMeaning
    ExceptionAn object thrown to signal that something went wrong, which interrupts normal flow
    throwRaises an exception
    try / catchtry guards code; catch handles a matching exception type
    Stack unwindingLeaving functions one by one while destroying their locals until a handler is found
    std::exceptionBase class of standard exceptions with a virtual what() message
    noexceptPromises a function will not throw
    Exception safetyBasic: 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.

    account.cpp
    #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.
    GuidelineWhy
    Throw by value, catch by const&Avoids slicing and copies
    Derive custom exceptions from std::exception typesCallers can catch generically
    Order catch blocks from most specific to most generalThe first matching handler wins
    Never throw from a destructorIt can terminate the program during unwinding
    Use RAII, not manual cleanup, in code that can throwDestructors 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.

    RequirementConcepts used
    Items (Book, Magazine, DVD) share an interface with virtual double lateFee(int days) const = 0Abstract 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 memberEncapsulation, composition
    Borrowing an unavailable item throws ItemUnavailableExceptions
    Find items by title using algorithms and lambdasSTL algorithms
    Print members and items with operator<<Operator overloading
    Save and load all data from a text fileFile I/O with RAII streams

    Skeleton to start from

    library.cpp
    #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.
    MilestoneGoal
    1Items and the Library compile and print the catalogue
    2Member class, borrow and return with the 3-item limit
    3Exceptions for unavailable items and limit exceeded
    4Fees through polymorphism, search with find_if
    5Save 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::exception types
    • 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&.

    divide.cpp
    #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?

    What happens to local objects when an exception leaves a function?

    Which should NEVER throw an exception?

    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 new and freed with delete.
    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

    1. Write a String class with deep copy and move, and test it under -fsanitize=address.
    2. Convert an old raw-pointer program to unique_ptr and shared_ptr.
    3. Create a generic Matrix<T> template with operator+ and operator<<.
    4. Implement Observer with std::function callbacks.
    5. Finish the Library Management System capstone.

    Course complete

    Finish the capstone, then revisit the roadmap and pick a new challenge.

    Back to roadmap