Topic 33 of 83
Overloading
Overview
Function overloading allows multiple functions to have the exact same name, as long as they have different parameters (type, number, or order). It is a form of compile-time polymorphism.
Syntax
cpp
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }Common Pitfalls
- Ambiguous calls: If you overload `func(float)` and `func(double)` and call `func(5.5)`, the compiler might not know which to pick (though 5.5 is double by default).
Interview Tips
- You cannot overload a function based purely on its return type. The parameter list MUST be different.
Real-World Example
A unified print function handling multiple data types.
example
cpp
#include <iostream>
#include <string>
using namespace std;
void display(int i) { cout << "Integer: " << i << endl; }
void display(double f) { cout << "Float: " << f << endl; }
void display(string s) { cout << "String: " << s << endl; }
int main() {
display(5);
display(3.14);
display("Hello");
return 0;
}