Overloading in C++
Function Overloading in C++
Whenever same method name is exiting multiple times in the same class with different number of parameter or different order of parameters or different types of parameters is known as method overloading.
Why method Overloading
Suppose we have to perform addition of given number but there can be any number of arguments, if we write method such as a(int, int)for two arguments, b(int, int, int) for three arguments then it is very difficult for you and other programmer to understand purpose or behaviors of method they can not identify purpose of method. So we use method overloading to easily figure out the program. For example above two methods we can write sum(int, int) and sum(int, int, int) using method overloading concept.
Syntax
class class_Name { Returntype method() { ........... ........... } Returntype method(datatype1 variable1) { ........... ........... } Returntype method(datatype1 variable1, datatype2 variable2) { ........... ........... } };
Different ways to overload the method
There are two ways to overload the method in C++
- By changing number of arguments or parameters
- By changing the data type
By changing number of arguments
In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers.
Program Function Overloading in C++
#include<iostream.h> #include<conio.h> class Addition { public: void sum(int a, int b) { cout<<a+b; } void sum(int a, int b, int c) { cout<<a+b+c; } }; void main() { clrscr(); Addition obj; obj.sum(10, 20); cout<<endl; obj.sum(10, 20, 30); }
Output
30 60
By changing the data type
In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two float arguments.
Function Overloading Program in C++
#include<iostream.h> #include<conio.h> class Addition { public: void sum(int a, int b) { cout<<a+b; } void sum(float a, float b) { cout<<a+b+c; } }; void main() { clrscr(); Addition obj; obj.sum(10, 20); cout<<endl; obj.sum(10, 20, 30); }
Output
30 25.25
Note: The scope of overloading is within the class.