C++ Overloading (Function and Operator)
If we create two or more members having the same name but different in number or type of parameter, it is known as C++ overloading. In C++, we can overload:
- methods,
- constructors, and
- indexed properties
It is because these members have parameters only.
Types of overloading in C++ are:
- Function overloading
- Operator overloading

C++ Function Overloading
Function Overloading is defined as the process of having two or more functions with the same name, but different parameters are known as function overloading in C++. In function overloading, the function is redefined by using either different types of arguments or a different number of arguments. It is only through these differences compiler can differentiate between the functions.
C++ Function Overloading Example
Let's see the simple example of function overloading where we are changing number of arguments of add() method.
- #include <iostream>
- using namespace std;
- class Cal {
- public:
- static int add(int a,int b){
- return a + b;
- }
- static int add(int a, int b, int c)
- {
- return a + b + c;
- }
- };
- int main(void) {
- Cal C; // class object declaration.
- cout<<C.add(10, 20)<<endl;
- cout<<C.add(12, 20, 23);
- return 0;
- }
Output:-
30
55
C++ Operators Overloading
👉Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type. For example, C++ provides the ability to add the variables of the user-defined data type that is applied to the built-in data types.
👉The advantage of Operators overloading is to perform different operations on the same operand.
Operator that cannot be overloaded are as follows:
- Scope operator (::)
- Sizeof
- member selector(.)
- member pointer selector(*)
- ternary operator(?:)
Syntax of Operator Overloading:-
- return_type class_name : : operator op(argument_list)
- {
- // body of the function.
- }
C++ Operators Overloading Example
Let's see the simple example of operator overloading in C++. In this example, void operator ++ () operator function is defined (inside Test class).
- #include <iostream>
- using namespace std;
- class Test
- {
- private:
- int num;
- public:
- Test(): num(8){}
- void operator ++() {
- num = num+2;
- }
- void Print() {
- cout<<"The Count is: "<<num;
- }
- };
- int main()
- {
- Test tt;
- ++tt; // calling of a function "void operator ++()"
- tt.Print();
- return 0;
- }
The Count is: 10