Overloaded Subprograms Implementation
Overloaded Subprograms Implementation
Overloading occurs when multiple subprograms (functions or methods) share the same name
but differ in the number or types of parameters. It allows the same function name to perform
different tasks based on the input arguments.
In C++, overloaded functions are implemented using different parameter types or numbers of
parameters.
#include <iostream>
using namespace std;
int main() {
cout << "Adding integers: " << add(5, 10) << endl; // Calls int version
cout << "Adding floats: " << add(5.5f, 10.2f) << endl; // Calls float version
cout << "Adding strings: " << add("Hello, ", "World!") << endl; // Calls string version
return 0;
}
Output
Adding integers: 15
Adding floats: 15.7
Adding strings: Hello, World!
1. Compile-Time Resolution:
○The compiler selects the appropriate function based on the arguments provided
in the function call.
○ The selection is based on parameter types and number of parameters.
2. Signature Matching:
○ Each overloaded version has a unique signature (name + parameter types). For
example:
■ add(int, int)
■ add(float, float)
■ add(string, string)
3. Function Dispatch:
○ The compiler generates separate code for each overloaded version and ensures
the correct one is called at runtime.
Key Points
○ Simplifies code by allowing the same function name to handle different data
types or operations.
○ Improves code readability and maintainability.
3. Limitations:
○ In some cases, ambiguities can arise when the compiler cannot determine which
function to call.
Overloaded Subprograms in Other Languages
Java: Java also supports method overloading with similar rules.