C++ Overloading (Function and Operator) : Methods, Constructors, and Indexed Properties
C++ Overloading (Function and Operator) : Methods, Constructors, and Indexed Properties
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.
Function overloading
Operator overloading
The advantage of Function overloading is that it increases the readability of the program because you
don't need to use different names for the same action.
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;
}
However, for user-defined types (like: objects), you can redefine the way operator works. For example:
If there are two objects of a class that contains string as its data members. You can redefine the meaning
of + operator and use it to concatenate those strings.
This feature in C++ programming that allows programmer to redefine the meaning of an operator (when
they operate on class objects) is known as operator overloading.
Example: Operator overloading in C++ Programming
#include <iostream> Output
count: 6
using namespace std;
class Test
{
Explanation:
private:
This function is called when ++ operator operates
int count;
on the object of Test class (object t in this case).
public:
Test(): count(5){}
In the program, void operator ++ () operator
void operator ++()
function is defined (inside Test class).
{
count = count+1;
}
void Display() { cout<<"Count: "<<count; } This function
increments the
};
int main()
{
Test t;
// this calls "function void operator ++()"
value of count by 1
function
++t;
t.Display();
for t object.
return 0;
}
Things to remember
• Operator overloading allows you to redefine the way operator works for user-defined types only
(objects, structures). It cannot be used for built-in types (int, float, char etc.).
• Two operators = and & are already overloaded by default in C++. For example: To copy objects of
same class, you can directly use = operator. You do not need to create an operator function.
• Operator overloading cannot change the precedence and associatively of operators. However, if
you want to change the order of evaluation, parenthesis should be used.
• There are 4 operators that cannot be overloaded in C++. They are :: (scope resolution), . (member
selection), .* (member selection through pointer to function) and ?: (ternary operator).