C++ Polymorphism Tutorial
Polymorphism is a key feature of Object-Oriented Programming (OOP) that allows objects to be treated as instances of their parent class. It enables a single function to be used with different types of objects. In C++, polymorphism can be achieved through method overriding and virtual functions.
What is Polymorphism?
Polymorphism allows a function, method, or operator to behave differently based on the context, or the type of object it is acting upon.
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() { // Virtual function
cout << "Some generic animal sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override { // Method overriding
cout << "Bark!" << endl;
}
};
int main() {
Animal* animal = new Dog(); // Base class pointer to derived class object
animal->sound(); // Outputs: Bark!
delete animal;
return 0;
}
Types of Polymorphism
There are two main types of polymorphism in C++:
- Compile-time Polymorphism (Static Binding): Achieved through function overloading or operator overloading.
- Run-time Polymorphism (Dynamic Binding): Achieved through method overriding and virtual functions.
Method Overriding
Method overriding allows a derived class to provide a specific implementation for a function that is already defined in the base class.
class Base {
public:
virtual void show() {
cout << "Base class" << endl;
}
};
class Derived : public Base {
public:
void show() override { // Overriding base class method
cout << "Derived class" << endl;
}
};
int main() {
Base* base = new Derived();
base->show(); // Outputs: Derived class
delete base;
return 0;
}
Virtual Functions
A virtual function is a member function in the base class that you expect to override in derived classes. Declaring a function as virtual ensures that the correct function is called for an object, even when using base class pointers or references.
class Base {
public:
virtual void display() { // Virtual function
cout << "Base class display" << endl;
}
};
class Derived : public Base {
public:
void display() override { // Overriding virtual function
cout << "Derived class display" << endl;
}
};
int main() {
Base* basePtr;
Derived derivedObj;
basePtr = &derivedObj;
basePtr->display(); // Outputs: Derived class display
return 0;
}
Polymorphism and Constructors
Polymorphism does not work with constructors. The constructor of the base class is called when an object of the derived class is created. Therefore, you can't override constructors using polymorphism.