Cpp Overloading
# C++ Operator Overloading and Function Overloading
C++ allows you to specify multiple definitions for a **function** or an **operator** within the same scope, which are called **function overloading** and **operator overloading**, respectively.
An overloaded declaration is a declaration that has the same name as a previously declared function or method in the same scope, but with a different parameter list and definition (implementation).
When you call an **overloaded function** or **overloaded operator**, the compiler compares the types of the arguments you use with the parameter types in the definitions to decide which definition is the most suitable. The process of selecting the most appropriate overloaded function or overloaded operator is called **overloading resolution**.
## Function Overloading in C++
Within the same scope, you can declare several functions with the same name but with different functionality. However, these functions must have different formal parameters (i.e., different number, type, or order of parameters). You cannot overload a function solely based on a different return type.
In the following example, the function **print()** is used to output different data types:
## Example
```cpp
#include
using namespace std;
class printData {
public:
void print(int i) {
cout << "Integer: " << i << endl;
}
void print(double f) {
cout << "Float: " << f << endl;
}
void print(char c[]) {
cout << "String: " << c << endl;
}
};
int main(void) {
printData pd;
// Print integer
pd.print(5);
// Print float
pd.print(500.263);
// Print string
char c[] = "Hello C++";
pd.print(c);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Integer: 5
Float: 500.263
String: Hello C++
## Operator Overloading in C++
You can redefine or overload most of the built-in operators in C++. This allows you to use operators with user-defined types.
An overloaded operator is a special function with a name formed by the keyword `operator` followed by the operator symbol to be overloaded. Like any other function, an overloaded operator has a return type and a parameter list.
```cpp
Box operator+(const Box&);
This declares the addition operator for adding two `Box` objects and returning the final `Box` object. Most overloaded operators can be defined as ordinary non-member functions or as class member functions. If we define the above function as a non-member function of the class, we need to pass two arguments for each operation, as shown below:
```cpp
Box operator+(const Box& b1, const Box& b2) {
Box box;
box.length = b1.length + b2.length;
box.breadth = b1.breadth + b2.breadth;
box.height = b1.height + b2.height;
return box;
}
YouTip