AWS Global Infrastructure

### Programming & Frameworks

Topics Covered
• C Programming and Data Structures (17 Blogs)
• Comprehensive Java Course (4 Blogs)
• Java/J2EE and SOA (339 Blogs)
• Spring Framework (8 Blogs)
SEE MORE

# How To Implement Operator Overloading in c++? How To Implement Operator Overloading in c++?

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,

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. 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(?:)

```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.

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.

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

• Overloading binary operator using a friend function.

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;
}
// 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: 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.

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;
}
// 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;
h3 = h1 + h2;
cout << "Sum of  Feet & Inches: " << h3.feet << "'" << h3.inch << endl;
return 0;
}
```

Output: 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.

• 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. REGISTER FOR FREE WEBINAR
Send OTP Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month

### Subscribe to our Newsletter, and get personalized recommendations. #### How To Implement Operator Overloading in c++?

edureka.co
{"ft_lang_label":"__label__en","ft_lang_prob":0.8523673,"math_prob":0.9506541,"size":6766,"snap":"2022-40-2023-06","text_gpt3_token_len":1503,"char_repetition_ratio":0.19417332,"word_repetition_ratio":0.07266436,"special_character_ratio":0.23751108,"punctuation_ratio":0.115384616,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9759031,"pos_list":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],"im_url_duplicate_count":[null,null,null,null,null,5,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-10-01T08:28:56Z\",\"WARC-Record-ID\":\"<urn:uuid:1d028817-adaf-4d21-8394-8eb4e0213df9>\",\"Content-Length\":\"199580\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:413585f8-969a-44c8-8ca7-31e845806c98>\",\"WARC-Concurrent-To\":\"<urn:uuid:0286e765-eb39-42a6-97f7-c0b48949d701>\",\"WARC-IP-Address\":\"52.85.151.108\",\"WARC-Target-URI\":\"https://www.edureka.co/blog/operator-overloading-in-cpp/\",\"WARC-Payload-Digest\":\"sha1:ZPNMIKN2WN6IIQRWWBFEGVRF56FM3MNN\",\"WARC-Block-Digest\":\"sha1:2NDTYFWNEQYNHMKD6EIPCV3UHBLQMNBD\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-40/CC-MAIN-2022-40_segments_1664030335573.50_warc_CC-MAIN-20221001070422-20221001100422-00390.warc.gz\"}"}