Overloading refers to use of same thing for different purpose. C++ provides the concept of overloading where we provides more than one definition for a single function or operator. We can categorized C++ overloading in two types:
- Function Overloading
- Operator Overloading
Let us discuss the both types of overloading one by one:
- Function Overloading refers to creating number of functions with the same name which perform different tasks.
- In Function overloading we can create number of functions with the name but either number of arguments or type of arguments must be different.
- Return type does not play any role in function overloading .When we have number of overloaded functions in a program, which function has to be call is determined by compiler by either checking type of argument or number of argument.
Here is a simple example of Function overloading:
void display(int a)
void display(double a)
In the above program we overloaded function display which takes a single parameter of type int and double. In function call display(5), int version of display is called because 5 is an integer. In function call display(5.5f) compiler look for an overloaded function display which takes float type argument but it fails and overloaded function display with double type value is called. In function call display(9.80), double version of display is called because 9.80 is a double value. In function call display('A') compiler searches for the an overloaded display function which takes a parameter of type char but it fails as there is no such overloaded function. so it does integral promotion from char to integer and calls the int version of display function displaying ASCII value of 'A' that is 65.So the output of the above program is as follows:
- Operator Overloading refers to overloading of one operator for many different purpose.
- It is one of the powerful feature of the C++ which give additional meaning to built-in standard operator like +,-,*,/,>,<,<=,>= etc.
- The syntax of overloading an operator and writing new overloaded operator function is as follows:
- In the above syntax:
- operator is a keyword and must be specified.
- operator-symbol represents the operator which we want to overload.
- Here is the list of some operators that can be overloaded and some that cannot be overloaded as sown in the tables given below: Operators that can be overloaded Operators that cannot be overloaded
- Here is an example of overloading of a binary operator that is '+':
static int count;
cout<<"Enter the number for object"<<++count<<endl;
int operator +(demo_sum)
cout<<"The num is"<<num<<endl;
cout<<"The sum of two object's num is"<<sum<<endl;
The output of the above program is as follows:
Enter the number for object2
The num is 20
The num is 30
The sum of two object's num is 50