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.
Definitions
| Term | Meaning |
|---|---|
| Inheritance | A 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 relationship | Inheritance models "a Dog is an Animal". Use it only when this sentence is true |
protected | Accessible inside the class and in classes derived from it, but not from outside |
| Constructor chaining | The 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
#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 inheritance | protected inheritance | private inheritance |
|---|---|---|---|
public | public | protected | private |
protected | protected | protected | private |
private | not accessible | not accessible | not accessible |
Types of inheritance
| Type | Shape | Example |
|---|---|---|
| Single | B inherits A | Dog : Animal |
| Multilevel | C inherits B inherits A | Puppy : Dog : Animal |
| Multiple | C inherits A and B | Duck : Swimmer, Flyer |
| Hierarchical | Many classes inherit one base | Dog, Cat, Bird : Animal |
| Hybrid | A mix, often forming a diamond | Two 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 protectedmembers 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) {}.
#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?
The base part must exist first, so the base constructor runs before the derived one.
Which member can a derived class use but outside code cannot?
protected is for derived classes. private is not even accessible to them.
What fixes the diamond problem?
virtual public inheritance makes the shared base appear only once.
Module 2
Polymorphism and virtual functions
One interface, many behaviours chosen at run time.
Definitions
| Term | Meaning |
|---|---|
| Polymorphism | "Many forms": the same call behaves differently depending on the object |
| Compile-time (static) polymorphism | Resolved by the compiler: function overloading, operator overloading, templates |
| Run-time (dynamic) polymorphism | Resolved while the program runs through virtual functions |
| Virtual function | A base-class function marked virtual that derived classes may override |
| Override | A derived function with the same signature that replaces the base version |
| vtable / vptr | A per-class table of virtual function addresses and the hidden per-object pointer to it |
| Late binding | Choosing the function to call at run time |
| Overloading | Overriding | |
|---|---|---|
| Where | Same class, same name, different parameters | Derived class, same name and same parameters |
| Resolved | At compile time | At run time (with virtual) |
| Needs inheritance | No | Yes |
Step through how one pointer calls two different functions:
Polymorphism in a loop
#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;
}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.
#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;
}~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
| Mistake | What happens | Fix |
|---|---|---|
Forgetting virtual in the base | Base version always runs when called through a base pointer | Add virtual to the base function |
Different signature in derived (a missing const, other parameter type) | You created a new function and hid the base one | Use override, the compiler will report the mismatch |
Copying into a base variable (Animal a = dog;) | Slicing: virtual dispatch is lost | Use a pointer or reference |
| Calling a virtual function inside a constructor | Runs the version of the class being built, not the final derived one | Avoid virtual calls in constructors and destructors |
Key takeaways
- Mark base functions
virtualand derived onesoverride - 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;
#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?
Virtual functions use the vtable so the real object decides.
What does the override keyword do?
It prevents silent signature mismatches.
Why make a base destructor virtual?
Otherwise only the base destructor runs and the derived part leaks.
Module 3
Abstract classes and interfaces
Define what a class must do without saying how.
Definitions
| Term | Meaning | Syntax |
|---|---|---|
| Pure virtual function | A virtual function with no body in the base class; derived classes must provide one | virtual double area() const = 0; |
| Abstract class | A class with at least one pure virtual function. You cannot create objects of it, only use it as a base | class Shape { ... }; |
| Concrete class | A class that implements every pure virtual function and can be instantiated | class Circle : public Shape |
| Interface | By convention an abstract class with only pure virtual functions and no data | class Printable |
| Abstraction | Exposing 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.
#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
#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 class | Concrete class | |
|---|---|---|
| Object creation | Not allowed | Allowed |
| Pure virtual functions | At least one | None left unimplemented |
| Can have data and normal functions | Yes | Yes |
| Typical role | Contract plus shared code | Real implementation |
Key takeaways
= 0marks 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.
#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?
A = 0 function makes the class abstract.
Can you create an object of an abstract class?
You can only create objects of concrete derived classes.
Module 4
Operator overloading
Make +, ==, << and [] work naturally on your own types.
Definitions
| Term | Meaning |
|---|---|
| Operator overloading | Giving an existing operator (+, ==, <<…) a meaning for your own class |
| Operator function | A function named operator followed by the symbol: operator+ |
| Member operator | Defined inside the class; the left operand is *this |
| Non-member (friend) operator | Defined outside the class when the left operand is not your type, for example cout << v |
| Return by value / by reference | Arithmetic 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
#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;
}(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
| Operator | Typical signature | Use |
|---|---|---|
[] | T& operator[](size_t i) | Index into a container class |
() | int operator()(int x) const | Function objects (functors) |
++ prefix | T& operator++() | Increment, return the updated object |
++ postfix | T 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&) const | Lets sort and map order your objects |
Key takeaways
- Operator functions are named
operator+,operator==, and so on - Binary arithmetic:
constmember 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<<.
#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?
Member operators always have the object on the left, but here the stream is on the left.
Which operator can NOT be overloaded?
::, ., .*, ?: and sizeof cannot be overloaded.
How does the compiler treat a + b for a class with a member operator+?
The left operand becomes *this.
Module 5
static, friend and composition
Share data across objects, grant trusted access and build objects from other objects.
Definitions
| Term | Meaning |
|---|---|
| static data member | One variable shared by all objects of the class, not copied into each object |
| static member function | A function that belongs to the class itself. It has no this and can only touch static members |
| friend function / class | A 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 |
| Aggregation | A 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.
#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.
#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.
#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) | |
|---|---|---|
| Relationship | Dog is an Animal | Car has an Engine |
| Coupling | Tight: derived depends on base internals | Loose: only the public interface of the part |
| Change later | Hard: base changes ripple down | Easy: swap the part |
| Rule of thumb | Use for true is-a and polymorphism | Prefer by default |
Key takeaways
- A static data member is shared by all objects and defined once outside the class
- A static function has no
thisand is called asClass::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.
#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?
There is exactly one, shared by the whole class.
Which relationship does a Car having an Engine represent?
The Car contains an Engine member: has-a.
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
= 0and 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
- Build a
Shapehierarchy (Circle, Rectangle, Triangle) and a function that prints the largest area. - Implement a
Vector2Dwith+ - * ==(scalar multiply) and<<. - Create a
Paymentinterface with three implementations and a checkout function. - Write a class hierarchy where every constructor and destructor prints, and predict the output order before running.
- 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