![]() |
VOOZH | about |
In C++, method overloading refers to defining multiple functions within the same class with the same name but different parameter lists. It allows a class to provide different behaviours for a method depending on the arguments passed to it. This is a form of compile-time polymorphism.
Method overloading allows a class to have more than one function with the same name but differing in:
Sum of 2 + 3: 5 Sum of 1 + 2 + 3: 6 Sum of 2.5 + 3.5: 6
The compiler determines at compile time which method to call based on:
For example:
calc.add(2, 3) calls add(int, int)
calc.add(2.5, 3.5) calls add(double, double)
Keep in mind that return type alone cannot differentiate overloaded methods. It is because if you call the function without specifying the type of variable that stores it return value (which is a valid function calling), then there is no way compiler can determine which function is called.
Also, default arguments in overloaded methods can cause ambiguity:
Just like normal functions, parameterized constructors can also be overloaded on the basis of its parameters.
Example:
Rectangle created with width = 10 and height = 20 Square created with side = 15 Default rectangle created (width = 0, height = 0) Area of rect1: 200 Area of rect2: 225 Area of rect3: 0
Method overloading have following main advantages: