Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Introduction to Polymorphism in C++

What is Polymorphism?

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It is the ability of different objects to respond to the same function call in different ways. In C++, polymorphism is primarily achieved through function overloading, operator overloading, and inheritance.

Types of Polymorphism

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

  • Compile-Time Polymorphism: Achieved through function overloading and operator overloading.
  • Run-Time Polymorphism: Achieved through inheritance and virtual functions.

Compile-Time Polymorphism

Compile-time polymorphism is achieved by function overloading and operator overloading. This type of polymorphism is resolved during compile time.

Function Overloading

Function overloading allows multiple functions with the same name but different parameters to be defined. The correct function to be invoked is determined by the arguments passed at compile time.

#include <iostream>
using namespace std;

class Print {
public:
    void show(int i) {
        cout << "Integer: " << i << endl;
    }

    void show(double d) {
        cout << "Double: " << d << endl;
    }

    void show(string s) {
        cout << "String: " << s << endl;
    }
};

int main() {
    Print p;
    p.show(5);
    p.show(5.5);
    p.show("Hello");
    return 0;
}
                
Output:
Integer: 5
Double: 5.5
String: Hello

Run-Time Polymorphism

Run-time polymorphism is achieved through inheritance and virtual functions. This type of polymorphism is resolved during runtime.

Virtual Functions

A virtual function is a member function in the base class that you expect to override in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.

#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;
    b->show();
    return 0;
}
                
Output:
Derived class

Advantages of Polymorphism

  • Increases flexibility and maintainability of code.
  • Makes it easier to add new features or change existing functionality.
  • Promotes code reusability.

Conclusion

Polymorphism is a powerful feature of C++ that allows for flexible and maintainable code. By understanding and utilizing both compile-time and run-time polymorphism, you can create programs that are easier to extend and maintain.