METHOD OVERLOADING IN C++ (Simple Explanation)
What is Method Overloading?
---------------------------
Method Overloading means:
Creating multiple functions with the same name but different parameters in the same class.
C++ decides which function to run based on the number or type of arguments.
Why Use It?
-----------
- To perform similar tasks with different input types or numbers.
- Makes code cleaner and more readable.
Rules of Method Overloading
---------------------------
You can overload a method by changing:
1. Number of parameters -> add(int) vs add(int, int)
2. Type of parameters -> add(int) vs add(float)
3. Order of parameters -> add(int, float) vs add(float, int)
Note: Return type alone cannot be used to overload a method.
Example in C++:
---------------
#include <iostream>
using namespace std;
class Calculator {
public:
void add(int a, int b) {
cout << "Sum (int): " << a + b << endl;
void add(float a, float b) {
cout << "Sum (float): " << a + b << endl;
void add(int a, int b, int c) {
cout << "Sum of 3 ints: " << a + b + c << endl;
};
int main() {
Calculator calc;
calc.add(2, 3);
calc.add(2.5f, 3.5f);
calc.add(1, 2, 3);
Types of Method Overloading:
----------------------------
Technically in C++, there's only one type: Function Overloading.
But based on how it's done:
1. Based on parameters count
2. Based on parameters type
3. Based on parameters order
What is NOT Allowed:
---------------------
class Example {
public:
int show() {
return 1;
float show() { // Error: only return type is different
return 1.5;
};