Who doesnot love syntactic sugar ? After all they make our code look more beautiful.So let us discuss how to overload operators in C++
How to Overload Operators in C++
What if I tell you ,You can use most of the operator in C++ not only with built in type but with the type you defined yourself (Classes are user defined type) .Yes you got it right , operator overloading lets you define the meaning of an operator when used to operands of user defined type(classes)
Overloaded operator are nothing else than a function (however a special one) with a special keyword operator followed by the symbol for the operator to be overloaded.
As I already mentioned that overloaded opeartors are a function so they definetly have a return type,parameter(s) and a body.
It should look something like this:
returnType operator Symbol(){}
returnType operator Symbol(){}
As an example:
int operator +(){
//body
}
Let us now overload plus operator (+) for our class .
1.#include<iostream>
2.using namespace std;
3.4.class A{
5.public:
6.int x=5;
7.};
8.class B{
9.int y=4;
10.public:
11.int operator +(A obj2){
12.int sum = y + obj2.x;
13.return sum;
14.}
15.};
16.int main(){
17.A obj1;
18.B obj2;
19.int sum = obj2+obj1;
20.cout<<"The sum is "<<sum;
21.}
The output of this code is :
The sum is 9
Lets see whats going on there.
We have defined our own classes ( A and B at line 4 and 8 respectively).A has a public member(no data hiding we are learning operator overloading) of x with value initialized to 5. Another class B has a private member y with value initialized to 4 . It also has a method (member function) . Oh! that is a special one. We can clearly see the keyword operator along with the a + sign . This is how we distinguish a overloaded operator ( a easy work though) . It takes a single parameter (Will talk about parameters below) which is an object of class A type.The function does something to add two numbers store it into a variable sum.The function then returns sum.
In our main function we created instances of our classes .(Objects are the instance of classes.)
Line 19 is a special one here.
int sum = obj2+obj1;
Feels like we are adding something here.Indeed we are.But obj2 and obj1 are non built in type.You are seeing it right. I am adding two objects here . This is what we call operator overloading (I will talk about its naming later in this post )
The 19th line is equivalent to :
int sum = obj2.operator+(obj1);
Isn't it similar to a normal function call. However we mostly use previously used syntax(19th one).
Deciding the parameters for overloaded operator
It should be noted that : An overloaded operator has the same number of parameters as the operator has operand.
For unary operator it should have one parameter.
For binary operator it should have two parameters.
I'd be very sad if you didn't raise this question to yourself:
If a binary operator should have two parameters then why we have only a single parameter passed for a binary plus(+) operator?
There is a plot twist here :
If a overloaded operator is a member function (function of a class) then the parameter lessens by one.
But why?Although we are passing a parameter the first parameter is always bound with the magical 'this' pointer.Which implies that our left hand operand should always be the object of the class in which the function is defined.
So If we change the 19th line to
int sum = obj1 + obj2 ;
It will be a blunder.
Special thanks to our special 'this' pointer we have a parameter lessen by One.
Keep these things in mind before you overload any operator
1. A operator function must either be a class member or should at least have a parameter of built in type,else the function would be wrong.
int operator -(int,int){}
The above line of code is a error because the operator - is predefined for two integers and we have no right to redefine it .
It should be noted that operator overloading is not valid for built in type.
2. We can overload only existing operator.
Looking above code you might have thought you can define and invent your own operator.But we cannot do so here.Only existing operator can be overloaded.
3.Not all operator can be overloaded .
::(scope resolution operator) , ?:(conditional operator) ,.*(member acess operator) , .(dot operator) cannot be overloaded.
Before I move to my last point let's talk a bit about Logical AND(&&) and logical OR(||) operator.
Logical AND(&&) and logical OR(||) operator.
You might be well known to these two operators:
Logical AND(&&)
if ((a==b)&&(b==c)){
//body goes here
}
Logical OR(||)
if (a == b || a == c){
//body goes here
}
Both of these operands have something in common.
These operator only move to the right operand if the left hand operand cannot produce a result. i.e.
In the above code(for logical AND) if the left operand evaluates to false the operator won't check for the second operand and the OR operator won't check the right side operand if the left operand evaluates to true .
So both of these operand guarantees the order in which the operands are evaluated.
4. It is advised not to overload such operator which gurantees the order in which operand are evaluated.This is because overloaded operator are just functions and we cannot gurantee the order of evaluation.
5.Since we are defining a function,we can have our own function definition.Always try to define your function which works equivalent to that used in defined type.
Never ever write a substraction code for a plus operator. This will be a spoiler for our syntactic sugar.So avoid those nasty stuffs.
You can read my article on the same topic at freecodecamp.org too. Check it here
That's It!
Happy Coding
💓❤️❤️Outstanding 😊
ReplyDeleteGood read!
ReplyDelete