Method Overloading - EduardoMSU/OOP-2143 GitHub Wiki

Method Overloading in Object-Oriented Programming (OOP)

What is Method Overloading?

Method overloading is a feature in object-oriented programming where multiple methods can have the same name but differ in the number or type of parameters. It allows a class to define more than one method with the same name, enabling different behaviors based on the input provided. Method overloading helps in improving code readability and reusability.


Key Characteristics of Method Overloading

Characteristic Description
Same Method Name Overloaded methods share the same name but differ in the type, number, or order of their parameters.
Compile-Time Polymorphism Overloading is a type of compile-time polymorphism, meaning the appropriate method is chosen at compile time based on the method signature.
Different Parameter Types The parameters in overloaded methods must differ in either the number of parameters or the types of parameters.
No Return Type Overloading Methods cannot be overloaded solely based on return type. The method signature must differ in parameters.
Method Selection The correct version of an overloaded method is selected by the compiler based on the arguments passed during the method call.

Syntax for Method Overloading in C++

Example of Method Overloading

#include <iostream>
using namespace std;

class Printer {
public:
    // Method to print an integer
    void print(int i) {
        cout << "Printing Integer: " << i << endl;
    }

    // Method to print a string
    void print(string s) {
        cout << "Printing String: " << s << endl;
    }

    // Method to print two integers
    void print(int i, int j) {
        cout << "Printing Two Integers: " << i << ", " << j << endl;
    }
};

int main() {
    Printer printer;

    // Calling overloaded methods
    printer.print(5);          // Calls print(int)
    printer.print("Hello");    // Calls print(string)
    printer.print(3, 4);       // Calls print(int, int)

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