Detailed Notes: Function Overloading & Operator
Overloading (C++)
1. Function Overloading
Function overloading allows multiple functions with the same name but different parameter lists. It is
a compile-time polymorphism.
Example:
#include <iostream>
using namespace std;
class Math {
public:
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
};
int main() {
Math m;
cout << [Link](2,3) << endl;
cout << [Link](2.5,3.5) << endl;
return 0;
}
2. Operator Overloading
Operator overloading allows redefining operators for user-defined types to give special meaning.
Example:
#include <iostream>
using namespace std;
class Number {
int value;
public:
Number(int v) { value = v; }
Number operator+(Number n) {
return Number(value + [Link]);
}
void display() {
cout << value << endl;
}
};
int main() {
Number n1(10), n2(20);
Number n3 = n1 + n2;
[Link]();
return 0;
}
3. Difference
Feature Function Overloading Operator Overloading
Concept Same function name Same operator
Type Compile-time Compile-time
Usage Functions Operators