🧩 C++ programming tutorial for beginners · Class 11 · Lesson 4 of 18 · Free
Polymorphism in C++ – Virtual Functions and Overriding
⏱ About 35 minutes · ▶ run real C++ here — nothing to install · no sign-in
In this lesson you will
- Tell compile-time polymorphism (overloading) apart from run-time polymorphism (virtual functions)
- Use virtual and override so a base pointer or reference calls the right derived function
- Write a pure virtual function and explain why a base class needs a virtual destructor
A school canteen takes payments in cash, by UPI and by card. The cashier just says "pay", and each payment type does its own thing. Polymorphism lets your code work the same way: one call, many correct behaviours.
What is polymorphism in C++?
Polymorphism means "many forms". The same name does different work depending on what it is used with.
C++ has two kinds. Compile-time polymorphism is chosen while compiling. Function overloading is the main example: many functions with the same name but different parameters.
Run-time polymorphism is chosen while the program runs. It uses virtual functions, which the next sections show.
Try it: add a third fee() that takes a string (the student's name) and prints a message.
3 months: Rs 4500 12 months with 10% off: Rs 16200
What is a virtual function in C++?
In Lesson 3 a Person* pointing at a Student still called Person's function. C++ looked at the pointer's type, not at the real object.
Mark the base function virtual. Now C++ checks the real object at run time and calls its version. This is run-time polymorphism.
In the derived class, write override after the function. It tells the compiler "this must replace a virtual function". If you get the name or parameters wrong, you get an error instead of a silent bug.
Try it: delete the word virtual and run. Both lines change to the base message.
Paid Rs 60 UPI: Rs 60 sent, no change needed
💡 Virtual calls work through a pointer (Payment*) or a reference (Payment&). If you copy a UpiPayment into a plain Payment variable, only the Payment part is copied. This is called slicing.
How do I use one array for different types of objects in C++?
The real power: keep base pointers to many kinds of objects in one array, and call the same function on each.
A painter quotes a price by wall area. Each shape knows its own area formula. The loop does not care which shape it holds.
To add a new shape later, you write one new class. The loop does not change at all.
Try it: add a Triangle class (area = base × height / 2) and put it in the array.
rectangle: 12 sq m circle: 0.785397 sq m rectangle: 2 sq m Paint cost at Rs 25 per sq m: Rs 369.635
💡 p->name() is a short way to write (*p).name(): call a member through a pointer.
What is a pure virtual function in C++?
"Area of a shape" makes no sense until you know which shape. So the base should not give a fake answer like 0.
Write = 0 instead of a body: virtual double area() const = 0;. This is a pure virtual function. It says "every derived class must write this".
A class with a pure virtual function is an abstract class. You cannot make objects of it, only of classes that fill in every pure virtual function. Lesson 13 goes deeper.
Try it: remove the fare() function from MetroCard and run. The compiler says MetroCard is now abstract too.
8 km costs Rs 17 8 km costs Rs 40 3 km costs Rs 20
💡 trip() is not virtual, but it calls fare(), which is. So each pass still uses its own fare.
Why does a base class need a virtual destructor in C++?
new creates an object that lives until you delete it. You often hold such objects through a base pointer: Shape* s = new Circle(2);. Lesson 14 shows safer smart pointers.
A destructor is a function that runs when an object is destroyed (Lesson 7). When you delete through a base pointer, C++ needs a virtual destructor to find the derived one.
Without it, deleting a derived object through a base pointer is undefined behaviour: the derived clean-up may never run. Rule: if a class has any virtual function, give it a virtual destructor.
Here both messages print, derived first, because the destructor is virtual.
Area: 12.5664 Circle cleaned up Shape cleaned up
🤔 Predict the output
Think like C++: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
#include <iostream>
using namespace std;
void show(int x) { cout << "int "; }
void show(double x) { cout << "double "; }
int main() {
show(5);
show(5.0);
cout << "\n";
return 0;
}
Question 2. What does this print?
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() const { cout << "..."; }
};
class Cow : public Animal {
public:
void sound() const override { cout << "Moo"; }
};
void speak(const Animal& a) { a.sound(); }
int main() {
Cow c;
Animal plain;
speak(c);
speak(plain);
cout << "\n";
return 0;
}
Question 3. What does this print?
#include <iostream>
#include <string>
using namespace std;
class Base {
public:
virtual string name() const { return "Base"; }
void hello() const { cout << "Hello from " << name() << "\n"; }
};
class Child : public Base {
public:
string name() const override { return "Child"; }
};
int main() {
Child c;
c.hello();
return 0;
}
🧩 Your challenge
Work out a school's monthly staff pay. Make an abstract class Staff with a name and a pure virtual double monthlyPay() const. Teacher gets a fixed salary. GuestLecturer gets hours × rate per hour. Put the objects in an array of Staff* and print each pay and the total: Mrs. Rao: Rs 45000 Mr. Sen: Rs 12000 Ms. Pillai: Rs 38000 Total: Rs 95000 (Mr. Sen is a guest lecturer: 24 hours at Rs 500.)
Mrs. Rao: Rs 45000 Mr. Sen: Rs 12000 Ms. Pillai: Rs 38000 Total: Rs 95000
⚠️ Common mistakes (and how to fix them)
❌ Wrong
#include <iostream>
using namespace std;
class Ticket {
public:
int price() const { return 100; }
};
class StudentTicket : public Ticket {
public:
int price() const { return 50; }
};
int main() {
StudentTicket s;
Ticket* t = &s;
cout << t->price() << "\n";
return 0;
}
Compiles and runs, but prints: 100 ⏎
✅ Right
#include <iostream>
using namespace std;
class Ticket {
public:
virtual ~Ticket() {}
virtual int price() const { return 100; }
};
class StudentTicket : public Ticket {
public:
int price() const override { return 50; }
};
int main() {
StudentTicket s;
Ticket* t = &s;
cout << t->price() << "\n";
return 0;
}
Without virtual, a Ticket* always calls Ticket's price(), even when it points at a StudentTicket. Mark the base function virtual.
❌ Wrong
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() const { return 0; }
};
class Square : public Shape {
double s = 3;
public:
double area() override { return s * s; }
};
int main() {
Square sq;
cout << sq.area() << "\n";
return 0;
}
Line 12: error: non-virtual member function marked 'override' hides virtual member function
✅ Right
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() const { return 0; }
};
class Square : public Shape {
double s = 3;
public:
double area() const override { return s * s; }
};
int main() {
Square sq;
cout << sq.area() << "\n";
return 0;
}
The derived function must match the base exactly, including const. override makes the compiler catch the mismatch instead of quietly making a new function.
❌ Wrong
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() const = 0;
};
int main() {
Shape s;
cout << s.area() << "\n";
return 0;
}
Line 10: error: variable type 'Shape' is an abstract class
✅ Right
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() const = 0;
};
class Square : public Shape {
public:
double area() const override { return 9; }
};
int main() {
Square s;
cout << s.area() << "\n";
return 0;
}
A class with a pure virtual function is abstract, so you cannot create an object of it. Create an object of a derived class that fills in the function.
📌 Remember
- Polymorphism: one name, many behaviours.
- Overloading (same name, different parameters) is chosen at compile time.
- virtual functions are chosen at run time, by the real object behind a pointer or reference.
- Write override in derived classes so the compiler checks the match.
- = 0 makes a pure virtual function and an abstract class.
- A class with virtual functions should have a virtual destructor.
Finished the quiz and the challenge?
Questions students ask
What is the difference between function overloading and overriding in C++?
Overloading means several functions with the same name but different parameters, usually in the same scope. Overriding means a derived class replaces a virtual function of its base with the same signature. Overloading is picked at compile time, overriding at run time.
Is the override keyword required in C++?
No, the code works without it. But override asks the compiler to check that you really replace a virtual function. It catches typos and missing const, so always use it.
Do virtual functions make C++ slow?
A virtual call costs a little more than a normal call, because the program looks up the right function at run time. For almost every program this cost is tiny. Use virtual where you need it.
What is a vtable in C++?
Most compilers make a hidden table of function addresses for each class with virtual functions. Each object stores a hidden pointer to its class's table, and a virtual call looks up the function there. The C++ standard does not require this, but it is how compilers usually do it.