Overloading - RJAE5/2143-OOP GitHub Wiki

Overloading

Overloading in C++ refers to the ability to define multiple functions or operators with the same name but different parameters. This allows for flexibility in how functions or operators can be used with different types or numbers of arguments, enhancing code readability and reuse. There are two main types of overloading in C++: function overloading and operator overloading.

Function Overloading: Multiple functions can have the same name but must differ in the number or types of parameters. The compiler selects the correct function based on the arguments passed during the call.

Operator Overloading: See Operator Overloading

Example

This example showcases how function overloading allows you to use the same function name display(), but with different argument types to handle different input data types in a clean and intuitive way.

#include <iostream>
using namespace std;

class Print 
{
public:
    // Overloaded function to print an integer
    void display(int i) 
    {
        cout << "Integer: " << i << endl;
    }

    // Overloaded function to print a double
    void display(double d) 
    {
        cout << "Double: " << d << endl;
    }

    // Overloaded function to print a string
    void display(const string& s) 
    {
        cout << "String: " << s << endl;
    }
};

int main() 
{
    Print p;

    // Calling overloaded functions with different argument types
    p.display(42);        // Calls display(int)
    p.display(3.1415926); // Calls display(double)
    p.display("Hello!");  // Calls display(string)

    return 0;
}

Code adapted from ChatGPT

The code snippet would produce the following output despite calling the same function with different parameters:

Integer: 42
Double: 3.1415926
String: Hello!

Important Notes

  • Overloading does NOT depend on return type, solely on input parameter matching.
  • Function overloading improves versatility, readability, and reuse.

Sources:

  1. https://www.geeksforgeeks.org/function-overloading-c/
  2. https://learn.microsoft.com/en-us/cpp/cpp/function-overloading?view=msvc-170
⚠️ **GitHub.com Fallback** ⚠️