C++ Function Overloading: A Practical Guide
C++ Function Overloading
Discover how C++ lets you define multiple functions with the same name but different signatures, illustrated with practical examples.
In C++, two functions may share the same name as long as their parameter lists differ in type, number, or order. These variants are called overloaded functions.
For instance:
// Same name, different arguments
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
All four declarations above represent a valid overload set. Note that return types are irrelevant for overload resolution; only the parameter list matters. For example:
// Compilation error: identical signatures
int test(int a) { }
double test(int b){ }
Here, both functions have the same name, same type, and same number of arguments, so the compiler rejects the duplicate.
Example 1: Overloading with Different Parameter Types
// Compute absolute value for int and float
#include <iostream>
using namespace std;
// float version
float absolute(float var){
return (var < 0.0f) ? -var : var;
}
// int version
int absolute(int var){
return (var < 0) ? -var : var;
}
int main(){
cout << "Absolute value of -5 = " << absolute(-5) << endl;
cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
return 0;
}
Output
Absolute value of -5 = 5 Absolute value of 5.5 = 5.5
This program overloads absolute(); the compiler selects the appropriate version based on the argument’s type.
Example 2: Overloading with Different Numbers of Parameters
#include <iostream>
using namespace std;
// Two-parameter version
void display(int var1, double var2){
cout << "Integer: " << var1;
cout << " & Double: " << var2 << endl;
}
// Single double parameter
void display(double var){
cout << "Double: " << var << endl;
}
// Single int parameter
void display(int var){
cout << "Integer: " << var << endl;
}
int main(){
int a = 5;
double b = 5.5;
display(a);
display(b);
display(a, b);
return 0;
}
Output
Integer: 5 Double: 5.5 Integer: 5 & Double: 5.5
The call to display() resolves to the correct overload based on the number and type of arguments.
Note: Standard library functions like sqrt() are heavily overloaded, accepting int, float, double, and more, providing flexibility to developers.
C Language
- Mastering C++ Functions: From Basics to Advanced Usage
- How to Pass Arrays to Functions in C++: A Practical Guide
- Master C++ Operator Overloading: Practical Examples & Best Practices
- C++ Function Overriding Explained – Practical Examples & Best Practices
- Mastering User-Defined Functions in C: A Step‑by‑Step Guide
- How to Pass 1D & 2D Arrays to Functions in C – A Practical Guide
- C++ Operator Overloading – A Practical Guide with Code Examples
- Mastering C Functions: Structure, Declaration, and Best Practices
- Mastering C++ Overloading: Functions & Operators Explained
- Understanding Polymorphism in C++: A Practical Guide