Polymorphism - EduardoMSU/OOP-2143 GitHub Wiki

Polymorphism in Object-Oriented Programming (OOP)

What is Polymorphism?

Polymorphism is one of the core principles of object-oriented programming that allows objects of different classes to be treated as objects of a common superclass. The word "polymorphism" means "many shapes," and in OOP, it enables a single interface to represent different types of objects or methods.

Polymorphism allows for method or operator overloading, and in a broader sense, it lets one method perform different tasks depending on the type of object that invokes it.


Key Types of Polymorphism

Type Description
Compile-time Polymorphism Also known as Method Overloading and Operator Overloading, resolved at compile time.
Runtime Polymorphism Occurs when a method is overridden in a subclass, and the method call is resolved at runtime. Often implemented using virtual functions.

Compile-time Polymorphism

Definition:

Compile-time polymorphism is resolved during compilation, and the correct method or operator is selected based on the method signature (e.g., method overloading or operator overloading).

Example of Method Overloading in C++

#include <iostream>
using namespace std;

class Printer {
public:
    // Overloading the 'print' method for different data types
    void print(int i) {
        cout << "Printing integer: " << i << endl;
    }

    void print(double d) {
        cout << "Printing double: " << d << endl;
    }

    void print(string s) {
        cout << "Printing string: " << s << endl;
    }
};

int main() {
    Printer p;

    p.print(10);           // Calls the integer version
    p.print(3.14);         // Calls the double version
    p.print("Hello!");     // Calls the string version

    return 0;
}
⚠️ **GitHub.com Fallback** ⚠️