Polymorphism in C++

Posted on December 15, 2023 by Vishesh Namdev
Python C C++ Java
C++ Programming

Polymorphism is a key concept in Object-Oriented Programming (OOP) that allows objects to be treated as instances of their base class, even when they are instances of derived classes. This concept enables a single interface to be used for different data types or objects. In C++, polymorphism is achieved through virtual functions and function overloading

There are two main types of polymorphism in C++:

Compile-Time Polymorphism (Static Binding):

Achieved through function overloading and operator overloading. The decision about which function to call is made at compile-time. It is also known as static polymorphism.

class StaticPolymorphism {Copy Code
public:
// Function Overloading
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {
return a + b;
}
};

int main() {
StaticPolymorphism obj;
int resultInt = obj.add(3, 5);
double resultDouble = obj.add(3.5, 5.2);
// ...
}

2. Run-Time Polymorphism (Dynamic Binding):

Achieved through virtual functions and pointers (or references) to base class objects. The decision about which function to call is made at runtime. It is also known as dynamic polymorphism.

class Animal {Copy Code
public:
// Virtual function
virtual void makeSound() const {
cout << "Some generic sound" << endl;
}
};

class Dog : public Animal {
public:
// Override the virtual function
void makeSound() const override {
cout << "Woof!" << endl;
}
};

int main() {
Animal* ptrAnimal = new Dog(); // Pointer to base class object
ptrAnimal->makeSound(); // Calls the overridden function in the derived class
delete ptrAnimal;
}

In the example above, the makeSound function is declared as virtual in the base class Animal, and it is overridden in the derived class Dog. When a Dog object is accessed through a pointer to the base class (Animal), the overridden function in the Dog class is called at runtime.

Some Basic Concepts of Inheritance:

(a). Virtual Function: A function declared in the base class with the virtual keyword. Intended to be overridden by derived classes. Provides a mechanism for dynamic binding.

(b). Override Keyword: Used in the derived class to indicate the intent to override a virtual function from the base class.Helps catch errors when the base class function is not overridden as intended.

(c). Pure Virtual Function: A virtual function with no implementation in the base class. Forces the derived classes to provide their own implementation. Declared using virtual returnType functionName() = 0;.

(d). Abstract Base Class: A class that contains at least one pure virtual function. Cannot be instantiated; it is meant to serve as a base class for other classes.

In C++, polymorphism is a powerful feature that enhances the flexibility and maintainability of code, making it a crucial aspect of object-oriented design.