CIPHERCODE.AI · C++ OOP INTERMEDIATE

C++ OOP intermediate

Reuse code, let objects decide their own behaviour at run time, and design with contracts instead of concrete classes.

  • 5 modules
  • 3 live explanations
  • Definitions, drills, quizzes

    You will be able to

    • Reuse code with inheritance and constructor chaining
    • Use virtual functions for run-time polymorphism
    • Design with abstract classes and interfaces
    • Overload operators and choose composition over inheritance

    Before you start

    You should be comfortable with classes, constructors and private data from the Beginner file. Each module opens with definitions, then a live explanation where the memory view shows several classes and the real objects at once. Predict the next step before pressing Next.

    Module 1

    Inheritance and protected access

    Build new classes from existing ones instead of rewriting code.

    About 2.5 hours

    Definitions

    TermMeaning
    InheritanceA mechanism where a new class (derived) acquires the data and functions of an existing class (base)
    Base class (parent, super)The class being inherited from
    Derived class (child, sub)The class that inherits and may add or change behaviour
    is-a relationshipInheritance models "a Dog is an Animal". Use it only when this sentence is true
    protectedAccessible inside the class and in classes derived from it, but not from outside
    Constructor chainingThe base constructor runs first, then the derived one

    Step through what happens when a Dog is created and destroyed. Watch the order of the messages.

    A realistic example: protected data and base constructors

    animals.cpp
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Animal {
    protected:
        string name;
    public:
        Animal(string n) : name(n) {}
        void eat() { cout << name << " is eating" << endl; }
    };
    
    class Dog : public Animal {
    public:
        Dog(string n) : Animal(n) {}
        void bark() { cout << name << " says Woof" << endl; }
    };
    
    int main() {
        Dog d("Rex");
        d.eat();
        d.bark();
        return 0;
    }
    name is protected, so Dog can use it but main cannot. Animal has no default constructor, so Dog must pass the argument up with : Animal(n) in its initializer list. If you forget, the compiler reports no matching function for call to Animal::Animal(). d.eat() is found in the base class.

    How inheritance mode changes access

    The word before the base class name (public, protected or private) caps how visible the base members become in the derived class. Use public inheritance for the normal is-a relationship.

    Base member is…public inheritanceprotected inheritanceprivate inheritance
    publicpublicprotectedprivate
    protectedprotectedprotectedprivate
    privatenot accessiblenot accessiblenot accessible

    Types of inheritance

    TypeShapeExample
    SingleB inherits ADog : Animal
    MultilevelC inherits B inherits APuppy : Dog : Animal
    MultipleC inherits A and BDuck : Swimmer, Flyer
    HierarchicalMany classes inherit one baseDog, Cat, Bird : Animal
    HybridA mix, often forming a diamondTwo parents sharing one grandparent

    Overriding and hiding

    A derived class can supply its own version of a base method with the same name. Without virtual this only hides the base version, and the choice is made by the pointer type at compile time. Module 2 explains the correct tool.

    Key takeaways

    • Derived classes reuse and extend base classes with class D : public B
    • Base constructors run first; destructors run in reverse order
    • Use : Base(args) to pass arguments to the base constructor
    • protected members are open to derived classes only
    • Use public inheritance only for true is-a relationships

    Practice

    Create a Vehicle class with protected wheels and a constructor. Derive Car (4 wheels) and Bike (2 wheels), each with info() printing the type and wheel count.

    Vehicle(int w) : wheels(w) {} and Car() : Vehicle(4) {}.

    vehicle.cpp
    #include <iostream>
    using namespace std;
    
    class Vehicle {
    protected:
        int wheels;
    public:
        Vehicle(int w) : wheels(w) {}
    };
    class Car : public Vehicle {
    public:
        Car() : Vehicle(4) {}
        void info() { cout << "Car with " << wheels << " wheels" << endl; }
    };
    class Bike : public Vehicle {
    public:
        Bike() : Vehicle(2) {}
        void info() { cout << "Bike with " << wheels << " wheels" << endl; }
    };
    
    int main() {
        Car c; Bike b;
        c.info();
        b.info();
        return 0;
    }

    Quick quiz

    In which order do constructors run for Dog : Animal?

    Which member can a derived class use but outside code cannot?

    What fixes the diamond problem?

    Module 2

    Polymorphism and virtual functions

    One interface, many behaviours chosen at run time.

    About 3 hours

    Definitions

    TermMeaning
    Polymorphism"Many forms": the same call behaves differently depending on the object
    Compile-time (static) polymorphismResolved by the compiler: function overloading, operator overloading, templates
    Run-time (dynamic) polymorphismResolved while the program runs through virtual functions
    Virtual functionA base-class function marked virtual that derived classes may override
    OverrideA derived function with the same signature that replaces the base version
    vtable / vptrA per-class table of virtual function addresses and the hidden per-object pointer to it
    Late bindingChoosing the function to call at run time
    OverloadingOverriding
    WhereSame class, same name, different parametersDerived class, same name and same parameters
    ResolvedAt compile timeAt run time (with virtual)
    Needs inheritanceNoYes

    Step through how one pointer calls two different functions:

    Polymorphism in a loop

    zoo.cpp
    #include <iostream>
    using namespace std;
    
    class Animal {
    public:
        virtual void speak() const { cout << "..." << endl; }
        virtual ~Animal() = default;
    };
    class Dog : public Animal {
    public:
        void speak() const override { cout << "Woof" << endl; }
    };
    class Cat : public Animal {
    public:
        void speak() const override { cout << "Meow" << endl; }
    };
    
    int main() {
        Dog d;
        Cat c;
        Animal* zoo[] = { &d, &c, &d };
        for (Animal* a : zoo) a->speak();
        return 0;
    }
    The array holds Animal* pointers, but the objects are really a Dog, a Cat and a Dog. The loop code never mentions Dog or Cat, so you can add a Bird later without changing it. const after speak() must match in every override. virtual ~Animal() = default; is explained below.

    Why virtual destructors matter

    If you delete a derived object through a base pointer and the base destructor is not virtual, the derived destructor is skipped (undefined behaviour). The derived part leaks. Rule: any class meant to be used as a base should have a virtual destructor.

    vdtor.cpp
    #include <iostream>
    using namespace std;
    
    class Base {
    public:
        virtual ~Base() { cout << "~Base" << endl; }
    };
    class Derived : public Base {
        int* data = new int[100];
    public:
        ~Derived() override { delete[] data; cout << "~Derived" << endl; }
    };
    
    int main() {
        Base* p = new Derived();
        delete p;
        return 0;
    }
    Because ~Base is virtual, delete p runs the destructor of the real type (~Derived) and then the base destructor. Without virtual the 100 ints would leak.

    Common mistakes

    MistakeWhat happensFix
    Forgetting virtual in the baseBase version always runs when called through a base pointerAdd virtual to the base function
    Different signature in derived (a missing const, other parameter type)You created a new function and hid the base oneUse override, the compiler will report the mismatch
    Copying into a base variable (Animal a = dog;)Slicing: virtual dispatch is lostUse a pointer or reference
    Calling a virtual function inside a constructorRuns the version of the class being built, not the final derived oneAvoid virtual calls in constructors and destructors

    Key takeaways

    • Mark base functions virtual and derived ones override
    • Call through a base pointer or reference to get run-time behaviour
    • The vptr and vtable pick the right function for the real object
    • Give every polymorphic base class a virtual destructor
    • Overloading is compile-time; overriding is run-time

    Practice

    Create a base class Shape with virtual double area() const returning 0. Derive Square and Circle (use 3.14). Store one of each in an array of Shape* and print every area in a loop.

    Square(double s) : side(s) {} and area() returns side * side. The loop is for (Shape* s : shapes) cout << s->area() << endl;

    shapes.cpp
    #include <iostream>
    using namespace std;
    
    class Shape {
    public:
        virtual double area() const { return 0; }
        virtual ~Shape() = default;
    };
    class Square : public Shape {
        double side;
    public:
        Square(double s) : side(s) {}
        double area() const override { return side * side; }
    };
    class Circle : public Shape {
        double r;
    public:
        Circle(double x) : r(x) {}
        double area() const override { return 3.14 * r * r; }
    };
    
    int main() {
        Square sq(4);
        Circle ci(2);
        Shape* shapes[] = { &sq, &ci };
        for (Shape* s : shapes) cout << s->area() << endl;
        return 0;
    }

    Quick quiz

    Which call is resolved at run time?

    What does the override keyword do?

    Why make a base destructor virtual?

    Module 3

    Abstract classes and interfaces

    Define what a class must do without saying how.

    About 2 hours

    Definitions

    TermMeaningSyntax
    Pure virtual functionA virtual function with no body in the base class; derived classes must provide onevirtual double area() const = 0;
    Abstract classA class with at least one pure virtual function. You cannot create objects of it, only use it as a baseclass Shape { ... };
    Concrete classA class that implements every pure virtual function and can be instantiatedclass Circle : public Shape
    InterfaceBy convention an abstract class with only pure virtual functions and no dataclass Printable
    AbstractionExposing what something does and hiding how it does it

    An abstract class is a contract. Anyone who wants to be a Shape must promise to provide area(). Code that uses shapes depends on the contract, not on any one shape.

    abstract.cpp
    #include <iostream>
    #include <vector>
    using namespace std;
    
    class Shape {
    public:
        virtual double area() const = 0;
        virtual string name() 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; }
        string name() const override { return "Circle"; }
    };
    class Rect : public Shape {
        double w, h;
    public:
        Rect(double w, double h) : w(w), h(h) {}
        double area() const override { return w * h; }
        string name() const override { return "Rectangle"; }
    };
    
    void describe(const Shape& s) {
        cout << s.name() << " area = " << s.area() << endl;
    }
    
    int main() {
        Circle c(5);
        Rect r(3, 4);
        describe(c);
        describe(r);
        vector<const Shape*> all = { &c, &r };
        double total = 0;
        for (const Shape* s : all) total += s->area();
        cout << "Total = " << total << endl;
        return 0;
    }
    = 0 makes area() and name() pure virtual, so Shape s; would not compile. describe takes a const Shape&: it accepts any shape, now or in future, and never needs editing. The vector stores base pointers and the sum calls the right area() each time. Note that parameters r, w, h share names with members, which is legal in an initializer list: r(r) initialises the member with the parameter.

    An interface in practice

    payment.cpp
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Payment {
    public:
        virtual void pay(double amount) = 0;
        virtual ~Payment() = default;
    };
    class CardPayment : public Payment {
    public:
        void pay(double a) override { cout << "Card paid " << a << endl; }
    };
    class UpiPayment : public Payment {
    public:
        void pay(double a) override { cout << "UPI paid " << a << endl; }
    };
    
    void checkout(Payment& method, double total) {
        method.pay(total);
    }
    
    int main() {
        CardPayment card;
        UpiPayment upi;
        checkout(card, 499);
        checkout(upi, 250);
        return 0;
    }
    checkout works with the interface only. To add NetBanking later you write one new class. Nothing that already works is touched. This idea is the Open/Closed Principle you will meet in the Advanced file.
    Abstract classConcrete class
    Object creationNot allowedAllowed
    Pure virtual functionsAt least oneNone left unimplemented
    Can have data and normal functionsYesYes
    Typical roleContract plus shared codeReal implementation

    Key takeaways

    • = 0 marks a pure virtual function; the class becomes abstract
    • Abstract classes cannot be instantiated but can be used through pointers and references
    • A concrete class must implement every pure virtual function
    • Program to the interface so new types plug in without edits

    Practice

    Create an interface Logger with virtual void log(const string& msg) = 0. Implement ConsoleLogger (prints [console] msg) and FileLogger (prints [file] msg, simulate with cout). Write run(Logger&) that logs "started".

    Both derived classes override log with the same signature and const string& parameter.

    logger.cpp
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Logger {
    public:
        virtual void log(const string& msg) = 0;
        virtual ~Logger() = default;
    };
    class ConsoleLogger : public Logger {
    public:
        void log(const string& m) override { cout << "[console] " << m << endl; }
    };
    class FileLogger : public Logger {
    public:
        void log(const string& m) override { cout << "[file] " << m << endl; }
    };
    void run(Logger& l) { l.log("started"); }
    
    int main() {
        ConsoleLogger a; FileLogger b;
        run(a);
        run(b);
        return 0;
    }

    Quick quiz

    What makes a class abstract?

    Can you create an object of an abstract class?

    Module 4

    Operator overloading

    Make +, ==, << and [] work naturally on your own types.

    About 2.5 hours

    Definitions

    TermMeaning
    Operator overloadingGiving an existing operator (+, ==, <<…) a meaning for your own class
    Operator functionA function named operator followed by the symbol: operator+
    Member operatorDefined inside the class; the left operand is *this
    Non-member (friend) operatorDefined outside the class when the left operand is not your type, for example cout << v
    Return by value / by referenceArithmetic operators return a new object; assignment and stream operators return a reference for chaining

    Operators you cannot overload: :: . .* ?: sizeof. Step through how p + q is executed:

    A complete Vec class

    vec.cpp
    #include <iostream>
    using namespace std;
    
    class Vec {
    public:
        int x, y;
        Vec(int a = 0, int b = 0) : x(a), y(b) {}
    
        Vec operator+(const Vec& o) const { return Vec(x + o.x, y + o.y); }
        Vec operator-(const Vec& o) const { return Vec(x - o.x, y - o.y); }
        bool operator==(const Vec& o) const { return x == o.x && y == o.y; }
        Vec& operator+=(const Vec& o) { x += o.x; y += o.y; return *this; }
    
        friend ostream& operator<<(ostream& os, const Vec& v) {
            return os << "(" << v.x << ", " << v.y << ")";
        }
    };
    
    int main() {
        Vec a(1, 2), b(3, 4);
        cout << a + b << endl;
        cout << (a == b) << endl;
        a += b;
        cout << a << endl;
        cout << a - b << endl;
        return 0;
    }
    Default arguments (int a = 0, int b = 0) also give a default constructor. operator+ and operator- are const and return new objects. operator== returns bool. operator+= changes *this and returns a reference so you can write a += b += c. operator<< is a friend because the left operand is ostream, not a Vec; it returns the stream so cout << a << b chains. The output shows a + b = (4, 6), then a == b is 0 (false), a += b makes a = (4, 6), and a - b = (1, 2).

    Other operators you will overload

    OperatorTypical signatureUse
    []T& operator[](size_t i)Index into a container class
    ()int operator()(int x) constFunction objects (functors)
    ++ prefixT& operator++()Increment, return the updated object
    ++ postfixT operator++(int)The dummy int marks postfix; return the old value
    =T& operator=(const T&)Copy assignment (see Rule of Five)
    <bool operator<(const T&) constLets sort and map order your objects

    Key takeaways

    • Operator functions are named operator+, operator==, and so on
    • Binary arithmetic: const member returning a new object
    • << must be a non-member and return the stream by reference
    • Some operators (::, ., ?:, sizeof) cannot be overloaded
    • Keep the natural meaning

    Practice

    Write a Money class (rupees as int) with +, -, == and << printing Rs 150. Test Money(100) + Money(50).

    Copy the structure of the Vec example: a constructor, two const operators, and a friend operator<<.

    money.cpp
    #include <iostream>
    using namespace std;
    
    class Money {
        int rs;
    public:
        Money(int r = 0) : rs(r) {}
        Money operator+(const Money& o) const { return Money(rs + o.rs); }
        Money operator-(const Money& o) const { return Money(rs - o.rs); }
        bool operator==(const Money& o) const { return rs == o.rs; }
        friend ostream& operator<<(ostream& os, const Money& m) {
            return os << "Rs " << m.rs;
        }
    };
    
    int main() {
        cout << Money(100) + Money(50) << endl;
        return 0;
    }

    Quick quiz

    Why is operator<< for printing usually a friend or non-member?

    Which operator can NOT be overloaded?

    How does the compiler treat a + b for a class with a member operator+?

    Module 5

    static, friend and composition

    Share data across objects, grant trusted access and build objects from other objects.

    About 2.5 hours

    Definitions

    TermMeaning
    static data memberOne variable shared by all objects of the class, not copied into each object
    static member functionA function that belongs to the class itself. It has no this and can only touch static members
    friend function / classA function or class given special permission to see private and protected members
    Composition ("has-a")A class contains objects of other classes as members and the parts live and die with the whole
    AggregationA class holds a reference or pointer to objects that exist independently

    static members

    Normally each object has its own copy of every data member. A static member exists once for the whole class. It is perfect for counters, shared settings and constants. A static data member is declared in the class and defined once outside it.

    static.cpp
    #include <iostream>
    using namespace std;
    
    class Player {
        static int count;
    public:
        Player()  { ++count; }
        ~Player() { --count; }
        static int total() { return count; }
    };
    int Player::count = 0;
    
    int main() {
        Player a;
        Player b;
        cout << Player::total() << endl;
        {
            Player c;
            cout << Player::total() << endl;
        }
        cout << Player::total() << endl;
        return 0;
    }
    count exists once, no matter how many Players there are. int Player::count = 0; is its single definition. Player::total() is called on the class, no object needed. When c goes out of scope at the inner brace its destructor runs and the count drops back to 2. (Since C++17 you can write inline static int count = 0; inside the class instead.)

    friend

    A friend declaration inside a class gives an outside function access to its private members. It does not make the function a member. Use it sparingly: it deliberately weakens encapsulation, so reserve it for operators and tightly coupled helper classes.

    friend.cpp
    #include <iostream>
    using namespace std;
    
    class Secret {
        int code = 1234;
        friend void reveal(const Secret& s);
    };
    
    void reveal(const Secret& s) {
        cout << "Code is " << s.code << endl;
    }
    
    int main() {
        Secret s;
        reveal(s);
        return 0;
    }
    reveal is not a member of Secret, but the friend line allows it to read s.code. Any other function that tries the same gets a "private" error.

    Composition: building objects from objects

    Instead of inheriting, give a class a member that is another class. The outer class decides which of the inner object's features to expose.

    compose.cpp
    #include <iostream>
    using namespace std;
    
    class Engine {
    public:
        void start() { cout << "Engine on" << endl; }
    };
    class Wheels {
    public:
        void roll() { cout << "Wheels rolling" << endl; }
    };
    class Car {
        Engine engine;
        Wheels wheels;
    public:
        void drive() {
            engine.start();
            wheels.roll();
            cout << "Car is moving" << endl;
        }
    };
    
    int main() {
        Car c;
        c.drive();
        return 0;
    }
    Car contains an Engine and Wheels. Creating a Car creates them first, and destroying a Car destroys them after it. Users of Car only see drive(); the parts stay hidden.
    Inheritance (is-a)Composition (has-a)
    RelationshipDog is an AnimalCar has an Engine
    CouplingTight: derived depends on base internalsLoose: only the public interface of the part
    Change laterHard: base changes ripple downEasy: swap the part
    Rule of thumbUse for true is-a and polymorphismPrefer by default

    Key takeaways

    • A static data member is shared by all objects and defined once outside the class
    • A static function has no this and is called as Class::fn()
    • friend grants access to private members; use it sparingly
    • Composition (has-a) is usually more flexible than inheritance (is-a)

    Practice

    Make a Library class that contains a Book member (title) and a static counter Book::created that counts every Book constructed. Print the count after creating three books.

    Declare static int created; inside Book, define int Book::created = 0; outside, and increment it in the constructor.

    books.cpp
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Book {
    public:
        static int created;
        string title;
        Book(string t) : title(t) { ++created; }
    };
    int Book::created = 0;
    
    int main() {
        Book a("A"), b("B"), c("C");
        cout << Book::created << endl;
        return 0;
    }

    Quick quiz

    How many copies of a static data member exist for 100 objects?

    Which relationship does a Car having an Engine represent?

    REVISION · INTERMEDIATE

    Definition bank, exam questions and output drills

    Define the term first, then give a short example. Try the output questions before opening the answers.

    Intermediate C++ OOP definitions

    Inheritance
    A class acquiring the members of another class.
    Base / derived class
    The class inherited from, and the class that inherits.
    protected
    Access level that allows the class and its derived classes to use a member.
    Constructor chaining
    Base constructor runs before the derived constructor.
    Polymorphism
    The same call behaving differently depending on the object type.
    Virtual function
    A function resolved at run time using the object's real type.
    Override
    A derived function replacing a virtual base function (same signature).
    vtable / vptr
    The per-class table of virtual function addresses and the per-object pointer to it.
    Pure virtual function
    A virtual function with = 0 and no required body, forcing derived classes to implement it.
    Abstract class
    A class with at least one pure virtual function; cannot be instantiated.
    Interface
    An abstract class with only pure virtual functions.
    Operator overloading
    Defining the meaning of an operator for a user-defined type.
    Friend function
    A non-member allowed to access private members of a class.
    static member
    A member that belongs to the class, shared by all objects.
    Composition
    A class containing objects of other classes as members (has-a).
    Slicing
    Losing the derived part when a derived object is copied into a base object.
    Diamond problem
    Ambiguity when a class inherits the same base through two paths; solved with virtual inheritance.
    Late binding
    Deciding which function to call at run time.

    Exam-style questions with answers

    Q1. Difference between overloading and overriding?

    Answer: Overloading: same name, different parameters in the same scope, resolved at compile time. Overriding: a derived class redefines a virtual function with the same signature, resolved at run time.

    Q2. What is a virtual destructor and why is it needed?

    Answer: A destructor declared virtual in a base class. When deleting a derived object through a base pointer it makes C++ call the derived destructor first, preventing leaks and undefined behaviour.

    Q3. Can a constructor be virtual?

    Answer: No. A virtual call needs the object's vptr, which is only set up while the constructor runs. Use a factory function if you need virtual-like creation.

    Q4. What is the difference between an abstract class and an interface in C++?

    Answer: C++ has no interface keyword. An interface is an abstract class with only pure virtual functions and no data. An abstract class may also hold data and implemented functions.

    Q5. Order of constructors and destructors in inheritance?

    Answer: Constructors: base then derived. Destructors: derived then base.

    Q6. Which operators cannot be overloaded?

    Answer: ::, ., .*, ?: and sizeof.

    Q7. What is object slicing?

    Answer: Assigning or copying a derived object into a base object variable, which discards the derived members and virtual behaviour.

    Q8. Static versus non-static member function?

    Answer: A static function belongs to the class, has no this pointer, and can use only static members. A non-static function works on a specific object.

    Output prediction drills

    What does this print?
    class A { public: void f(){cout<<"A";} };
    class B : public A { public: void f(){cout<<"B";} };
    A* p = new B;
    p->f();

    Answer: A. f is not virtual, so the pointer type decides at compile time. Add virtual to get B.

    What does this print?
    struct A{ A(){cout<<"A";} ~A(){cout<<"a";} };
    struct B : A{ B(){cout<<"B";} ~B(){cout<<"b";} };
    int main(){ B x; }

    Answer: ABba. Constructors base-to-derived, destructors in reverse.

    Is this legal?
    class S{ virtual void f()=0; };
    S s;

    Answer: No. S is abstract, so S s; is a compile error.

    Practical assignments

    1. Build a Shape hierarchy (Circle, Rectangle, Triangle) and a function that prints the largest area.
    2. Implement a Vector2D with + - * == (scalar multiply) and <<.
    3. Create a Payment interface with three implementations and a checkout function.
    4. Write a class hierarchy where every constructor and destructor prints, and predict the output order before running.
    5. Add a static counter to a class that tracks live objects.

    Intermediate complete

    Next: pointers, the heap, smart pointers, templates and design patterns.

    Open Advanced