Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

OOP Part 4: Polymorphism

Lesson 36 of 53 in the free Foundation of C & C++ notes on Siksha Sarovar, written by Rohit Jangra.

"One Interface, Many Forms"

Polymorphism is the most advanced and magical concept in OOP. it allows you to treat different types of objects in a uniform way through a single interface.

1. Compile-Time Polymorphism

  • Function Overloading: Having multiple functions with the same name but different input types.
  • Operator Overloading: Making the + sign work for your custom objects (like adding two Matrix objects together).

2. Runtime Polymorphism (Virtual Functions)

This is the real power. It allows a Pointer to a Parent to call the Child's version of a function.

class Enemy {
    virtual void attack() { cout << "Basic hit"; }
};

class Boss : public Enemy {
    void attack() override { cout << "MEGA BLAST!"; }
};

Enemy *e = new Boss();
e->attack(); // Prints "MEGA BLAST!" because of the 'virtual' keyword.

Abstract Classes

Sometimes a parent class is just a concept and shouldn't be used to create objects. What does a "Generic Animal" look like? No one knows. You only know what a "Cat" or "Dog" looks like.

  • Pure Virtual Function: virtual void draw() = 0;
  • Any class with a pure virtual function is an Abstract Class and cannot be used to create objects.

Why does this matter?

It makes your code Extensible. You can write a function that takes a list of Shape* and draws them. You can add 100 new types of shapes later, and your drawing function will work perfectly without you changing a single line of its code!

Essential Rule: If your class has any virtual functions, your Destructor must also be virtual. If it's not, C++ might forget to delete the "child" parts of your object, causing a memory leak.