Run-time Polymorphism in C++
Introduction
Polymorphism is one of the four fundamental principles of Object-Oriented Programming (OOP). It allows methods to do different things based on the object it is acting upon. In this tutorial, we will delve into run-time polymorphism in C++.
What is Run-time Polymorphism?
Run-time polymorphism is a process in which a function call to the overridden method is resolved at runtime. This is achieved through the use of virtual functions and inheritance.
Virtual Functions
A virtual function is a function in a base class that is declared using the keyword virtual. It is used to achieve run-time polymorphism. When a base class declares a function as virtual, it allows derived classes to override that function.
Example
Consider the following example that demonstrates run-time polymorphism using virtual functions:
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() {
cout << "Base class" << endl;
}
};
class Derived : public Base {
public:
void show() override {
cout << "Derived class" << endl;
}
};
int main() {
Base* b;
Derived d;
b = &d;
// Virtual function, binded at runtime
b->show();
return 0;
}
The output of the above code will be:
Explanation
In the above example, the Base class contains a virtual function show(). The Derived class overrides this function. In the main() function, a pointer of type Base points to an object of the Derived class. When b->show() is called, it actually calls the show() function of the Derived class because the function is virtual and resolved at runtime.
Pure Virtual Functions and Abstract Classes
A pure virtual function is a function that has no implementation in the base class and must be overridden in the derived class. It is declared by assigning 0 in its declaration. A class containing pure virtual functions is called an abstract class.
Example
Here is an example to demonstrate pure virtual functions and abstract classes:
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() = 0; // Pure virtual function
};
class Derived : public Base {
public:
void show() override {
cout << "Derived class implementation of show()" << endl;
}
};
int main() {
Derived d;
d.show();
return 0;
}
The output of the above code will be:
Explanation
In the above example, the Base class contains a pure virtual function show(). The Derived class overrides this function and provides an implementation. Since Base contains a pure virtual function, it is an abstract class, and we cannot instantiate it directly.
Conclusion
Run-time polymorphism is a powerful feature in C++ that allows for dynamic method binding. By using virtual functions, you can create flexible and reusable code. Understanding and utilizing run-time polymorphism can significantly improve the design and maintainability of your code.
