C Programming and Data Structures (45 Blogs)

How To Implement Operator Overloading in c++?

Published on Aug 08,2019 379 Views
How To Implement Operator Overloading in c++?

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

In this article we will explore yet another object oriented concept that makes operator handling easy. That is we would be getting into the details of Operator Overloading in C++. Following pointers will be covered in this article,

So, let us get started with this article on Operator Overloading in C++.

Overloading in C++

If we create two or more member of the same class 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
  • indexed properties

It is because these members have parameters only.

Moving on with this article on Operator Overloading in C++.

Types of overloading in C++

  • Function overloading
  • Operator overloading

Overloading - Operator Overloading In C++ - Edureka

Moving on with this article on Operator Overloading in C++.

Why is operator overloading used?

C++ programs can be written without the knowledge of operator overloading. Then too, operator operating are profoundly used by programmers to make the program intuitive. For example,

We can replace the code like:

calculation = add(divide(a, b),multiply(a, b));

For equation

calculation = (a/b)+(a*b);

Operator overloading provides a simple and easy way for the development of new definitions for most of the operators in C++. With sufficient knowledge, we can almost create a new language of our own by the creative use of the function and operator overloading techniques. We can overload all the operators in C++ except the following:
● Scope operator (::)
● Size operator (Sizeof)
● member selector(.)
● member pointer selector(*)
● ternary operator(?:)

Syntax of Operator Overloading

return_type class_name  : : operator op(argument_list)  
{  
// function body
}  

Where the return type is the type of value returned by the function. class_name is the name of the class.

Moving on with this article on Operator Overloading in C++.

Implementing Operator Overloading in C++

Operator function must be either non-static (member function) or friend function to get overloaded. Operator overloading function can be applied on a member function if the left operand is an object of that class, but if the Left operand is different, then the Operator overloading function must be defined as a non-member function.
Operator overloading function can be made friend function if it requires access to the private and protected members of the class. For example, the operator op is an operator function where op is the operator being overloaded, and the operator is the keyword. Operator overloading can be achieved by implementing a function that can be either member function,non- member function or friend function.

What is the difference between operator functions and normal functions?

Operator functions are the same as normal functions. The only difference is, the name of an operator function is always operator keyword followed by the symbol of operator and operator functions are called when the corresponding operator is used.

Moving on with this article on Operator Overloading in C++.

Types of overloading approaches

Operator Overloading can be done by using three approaches, they are

  • Overloading unary operator.
  • Overloading binary operator.
  • Overloading binary operator using a friend function.

Moving on with this article on Operator Overloading in C++.

Overloading Unary Operator

Let us consider the unary ‘ – ‘ operator. A minus operator when used as a unary it requires only one operand. We know that this operator changes the sign of an operand when applied to a basic data variable. Let us see how to overload this operator so that it can be applied to an object in much the same way as it is applied to an int or float variable. The unary minus, when applied to an object, should decrement each of its data items.

Example:

#include <iostream> 
using namespace std; 
class Height { 
public:   
// Member Objects
int feet, inch;   
// Constructor to initialize the object's value 
Height(int f, int i) 
{ 
feet = f; 
inch = i; 
}   
// Overloading(-) operator to perform decrement 
// operation of Height object 
void operator-() 
{ 
feet--; 
inch--; 
cout << "Feet & Inches after decrement: " << feet << " ' " << inch <<endl; 
} 
};   
int main() 
{ 
//Declare and Initialize the constructor of class Height
Height h1(6, 2);   
//Use (-) unary operator by single operand 
-h1; 
return 0; 
} 

Output:

Output- Operator Overloading in c++- Edureka

Explanation:
In the above example, we overload ‘ – ’ unary operator to perform decrement in the two variables of Height class. We pass two parameters to the constructor and save their values in feet and inch variable. Then we define the operator overloading function ( void operator-()
) in which the two variables are decremented by one position.
When we write -h1 it calls the operator overloading function and decrements the values passed to the constructor.

Moving on with this article on Operator Overloading in C++.

Overloading Binary Operator

It is an overloading of an operator operating on two operands. Let’s take the same example of class Height, but this time, add two Height objects h1 and h2.

Example:

#include <iostream>   
using namespace std; 
class Height 
{ 
public: 
int feet, inch; 
Height() 
{ 
feet = 0; 
inch = 0; 
}   
Height(int f, int i) 
{ 
feet = f; 
inch = i; 
}   
// Overloading (+) operator to perform addition of 
// two distance object using binary operator
Height operator+(Height& d2) // Call by reference 
{ 
// Create an object to return 
Height h3;   
// Perform addition of feet and inches 
h3.feet = feet + d2.feet; 
h3.inch = inch + d2.inch; 
// Return the resulting object 
return h3; 
} 
};  
int main() 
{ 
Height h1(3, 7);   
Height h2(6, 1); 
Height h3;   
//Use overloaded operator 
h3 = h1 + h2; 
cout << "Sum of  Feet & Inches: " << h3.feet << "'" << h3.inch << endl; 
return 0; 
} 

Output:
Output- Operator Overloading in c++- Edureka

Explanation:
Height operator+(Height &h2), here returns_type of function is class Height thus it returns an object h3 of class Height. In the line h3 = h1 + h2, h1 calls the operator function of its classes objects and takes h2 as a parameter, then we apply h3.feet = feet + d2.feet; and h3.inch = inch + d2.inch; which stores the sum of values of the variables feet and inch in variables associated with the h3 object.
When the statement ‘h3 = h1 + h2’ invokes the operator overloaded function the object h1 took the responsibility of invoking the function and h2 plays the role of argument that is passed to the function. The above invocation statement is equivalent to h3 = h1.operator+(h2); therefore the data member of h2 are accessed directly and the data member of h2 (that is passed as an argument) are accessed using the dot operator.

Rules for Operator Overloading

  • Only the existing operators can be overloaded and new operators cannot be overloaded
  • The overloaded operator must contain at least one operand of the user-defined data type.
  • We do not use a friend function to overload certain operators. However, the member functions can be used to overload those operators.
  • When unary operators are overloaded through a member function they take no explicit arguments, but, if they are overloaded by a friend function they take one argument.
  • When binary operators are overloaded through a member function they take one explicit argument, and if they are overloaded through a friend function they take two explicit arguments.

Thus we have come to an end of this article on ‘Operator Overloading in C++’. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course are designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.

Comments
0 Comments

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.