🔄 Function Overloading in C++ (Same Name, Different Parameters)

Function Overloading in C++ | Same Name, Different Parameters

🔄 Function Overloading in C++ (Same Name, Different Parameters)

Function overloading is a powerful feature in C++ that allows you to define multiple functions with the same name but different parameter lists. This concept is widely used in object-oriented programming to increase code reusability, maintainability, and readability.

📘 What is Function Overloading?

Function overloading in C++ occurs when two or more functions in the same scope have the same name but different types or numbers of parameters. The compiler distinguishes these functions based on the number and types of arguments passed to them at the time of the function call.

It helps in designing intuitive and easy-to-understand code. For example, you can create an overloaded function to add two integers, two floats, or even concatenate two strings—using the same function name.

💡 Why Use Function Overloading?

  • Improves code clarity and readability
  • Reduces the need for multiple function names for similar tasks
  • Promotes reuse of logic with different data types or argument combinations
  • Makes your code more object-oriented and modular

📄 C++ Example: Function Overloading


#include <iostream>
using namespace std;

// Function to add two integers
int add(int a, int b) {
    return a + b;
}

// Function to add two floating-point numbers
float add(float a, float b) {
    return a + b;
}

// Function to add three integers
int add(int a, int b, int c) {
    return a + b + c;
}

int main() {
    cout << "Sum of 5 and 10 (int): " << add(5, 10) << endl;
    cout << "Sum of 2.5 and 4.5 (float): " << add(2.5f, 4.5f) << endl;
    cout << "Sum of 1, 2, 3 (int): " << add(1, 2, 3) << endl;
    return 0;
}
    

📝 Sample Output

Sum of 5 and 10 (int): 15
Sum of 2.5 and 4.5 (float): 7
Sum of 1, 2, 3 (int): 6

🧠 How It Works

  • The compiler chooses the right function based on the parameters passed.
  • add(int, int) is called when two integers are passed.
  • add(float, float) is called when two floats are passed.
  • add(int, int, int) is called when three integers are passed.

This technique makes your code dynamic and adaptable. In real-world applications, overloading is used in constructors, operators, and methods where the logic remains the same but inputs may vary.

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences