#16-Operator overloading in C++-Unary and Binary operator overloading

Operator overloading.

We have used the existing operators such as +,-,*,and / with the fundamental data types.

Fundamental data types are int,float,etc datatypes.

And in the same way, a need to use these operators with the user defined data type i.e objects of a class was arose. And after a lot of research in programming, now, we can use the existing operators with user defined data type.

And, this is called as operator overloading.

For eg-: in c3=c1+c2; + operator is said to be overloaded, if c1 and c2 are of class datatype; i.e they are objects of a class.

But, but, but, wait.

Exceptions are always there.

And in the same way, some exceptions arise in case of operator overloading. Some operators can’t be overloaded.

And those operators which can’t be overloaded are as follows.

  1. Dot operator
  2. Scope resolution operator
  3. Conditional operator
  4. Sizeof() operator

There are also some rules regarding operator overloading.

And the rules to follow while writing a program that involves operator overloading are as follows.

  1. Only the existing operator can be overloaded and new operators can’t be formed.
  2. One operand should be of user defined type. i.e 5+c1; c1=user defined.
  3. Unary operator can be overloaded through two ways. 1)member operator function and 2)friend function. When it is overloaded through member operator function, it takes NO argument. And while it is being overloaded through friend function, it takes 1 REFERENCE OBJECT as argument.
  4. binary operator can also be overloaded through two ways. a) through member operator function and b) through friend function. The binary operator overloading through member operator function takes ONE argument, while the binary operator overloading through friend function takes TWO arguments.
  5. Friend function is useful in many operator overloading problems. But, in some cases, we have exceptions where we can’t use friend function. So, the operators in which we can’t use friend functions are as follows.
  6. =
  7. ()
  8. []
  9. ->

Note that “=” is assignment operator.

“()” is function call operator.

“[]” is index operator.

“->” arrow operator.

Now, before entering into a lots of details about operator overloading, let’s see what types of questions can be asked in relation with this topic, in our examinations.

Even if you are not studying this for examination point of view, then also it is very important as you can get what we are going to learn in this article.

So, questions are as follows.

Q) Explain which operators can’t be overloaded in C++? Explain how a class type(user-defined type) of data can be converted to a basic data(inbuilt data) type? Write a program to concatenate two strings by overloading binary plus(+) operator.

Q) Define operator overloading. Write operator functions as member function of a class to overload arithmetic operator +, logical operator “<=” and stream operator “<<” to operate on objects of user defined type time(hr,min,sec).

Q) How do you convert user defined data type into a basic data type? Write a program to overload the relational operators to compare the length of two objects.

Q) How do you overload unary operator. Explain with example.

Q)Write a program that will convert the object from a class Rectangle to object of a class Polar using casting operator.

Q) Write a program having a class to represent money. The class should have two integer members to represent rupees and paisa. Overload + and – operators for adding and subtracting the objects. Then overload, >,<,== and != operators for comparing the objects.

Q) What is the disadvantage of using operator overloading in C++? Write a program to define a class Distance with necessary data members and functions. Then overload the relational operators to compare the two objects of Distance class.

Q)Write a program to add 2 matrices using the operator overloading.

Q) Write a program to overload (==,!=,>,<,>=,<=) to compare complex numbers.

Q) Write a program to convert object of a class that represents weight of gold in tola to object of class that represent wight in grams.

Use 1 tola=11.664 gm.

So, these are some questions. I will be solving almost all of the above problems. I will solve them in such a way that you can tackle any new questions about this topic, very easily.

Unary operator overloading:

What is unary operator?

The operator which is used with a single operand is called unary operator.

There are two types of unary operator.

  1. Unary post-fix
  2. Unary pre-fix

Now, let’s see its syntax for overloading.

Syntax for overloading unary prefix and unary postfix operator using member operator functions.

So, we see.

Its syntax is given as:

Class class_name

{

Private:

//data-member;

Public:

//other member functions

Return_type operator operator_symbol();

//for prefix

Return_type operator operator_symbol(int);

//for postfix

};

Return_type class_name::operator operator_symbol

{

//body of member operator function

}

Return_type class_name::operator operator_symbol(int i)

{

//body of member operator function

}

Again, let’s see syntax for overloading unary prefix and unary postfix operator using non-member operator function i.e friend function.

So the syntax to overload unary prefix, and unary postfix operator using friend function is as follows.

Class class_name

{

Private:

//data members

Public:

//other member-functions

Friend return_type operator operator_symbol(class_name)

Friend return_type operator symbol(int,class_name &)

};

Return_type operator operator symbol(class_name &object.name)

{

//body of the function

}

Return_type operator operator_symbol

{

//body of function

}

So, let’s see a program related to unary operator overloading.

Q) Write an example program for overloading unary prefix (++) using member operator function and unary prefix (–) using friend function.

Its output will come as follows.

So, let’s discuss about the above program.

Basically, what we are trying to do is to overload the unary prefix(++) using member function.

And overloading unary prefix(–) using friend function. prephoto.png

The above figure clearly shows what we need to do in this program.

And remember the rules that, operator overloading through member operator function takes no argument while the same operator overloading through friend function takes 1 reference object as an argument.

2.png

The above figure explains about the number of arguments, in operator overloading through non-member function and friend function.

So, till now, you must have got the basic framework of this program.

It will be like

1 member operator fxn to declare for ++.

1 friend function to declare for –.

And friend function+unary operator so, we will require a reference object.

So, the explanation starts now.

It all starts with the int main() function. inside it, as we can see; we at first, passed 10 to a parameterized constructor. Then, we initialize a default constructor.

After that, we called the unary operator ++ function by “++c1”. After this step, the “void operator ++()” will get called. And, that will increase the value of count.

Likewise, again coming back to the main() function, we can see that, we displayed the value of c1 object. And in this case, we will get c1=11.

After that, we called that friend function operator –….to overload it.

And we did that as-:

“c2=–c1”.

[[[[[[[[[[[ The syntax is very important.

We did this, because we are passing reference object.

If we only do –c1, that’ll do no justice for friend function. how will code::blocks recognize if it is designed for friend function or not.]]]]]]]]]

Now, “c2=–c1”, will invoke the operator function shown above.”counter operator –(counter &c1).

inside that, a temp object will be created. And in the count directory of that object(i mean to say inside temp.count);what we did was….to…–c1.count.

And, finally, we returned temp.

So, as soon as c1=11 will be passed there, it will go and store inside temp.count; but..but..but, we have to –c1.count to make the equation equal…so, as in prefix operator, we will first FIX and then CALCULATE.

so 11-1=10. And, 10 was stored in temp.count.

And we returned temp( here temp=temp.count+0+0…0)

ABA(my slang for saying “THEN/NOW”-pronounce it aw-baah;DUDE enjoy learning 🙂

And now, c2 is gonna be storing the value of –c1(=c1 ; remember;in prefix;first fix, then calculate)

so.so…so c2=10 –c1=10 but but but…..as soon as we finished the calculation, we must forget the operator — and be able to say that….c1 is also equals to 10.

Hence, c1.ret_count is going to return 10 as c1=10 and so is c2(rememeber c2 is also equals to 10).

Q)Write a program to overload the unary postfix ++ through member operator function and unary postfix — through friend function.

Understanding the question is a very much useful thing in programming.

[ One request-: subscribe to our website, by scrolling through the bottom.

We won’t spam your e-mail.]

So, I was talking about problem solving in programming.

According to the above question, we are asked to do the following things.

  1. Unary postfix++ using member fxn
  2. Unary postfix – using friend fxn.

So, you must have got a certain framework for what a program will look like.

And you will get its source code below.

SOURCE code lives here(edited this article too much….feeling really tired!!!)

 

So, it is now time to discuss about the working of the program.

It all starts with the int main function.

And inside that function, we can see that, we passed 10 into a parameterized constructor.->c1=10;

And then initialized c2’s count=0.

And then, we increased c1++; that means that, this will invoke the “void operator ++(int)” and that will increment the count. So, now count becomes 11.

Then, we can see that we showed that value=11. Now, “c2=c1–” will be invoked.

And, that will take us to the friend function (*remember we are using c2= just for making friend function happy…if we don’t do that, friend function will not even work properly)

and inside “temp.count”=11–…so that, the value =10.

now we just returned a value 10 to c1–; so c1 will be displayed as 10…

now c2=c1– will work…and you know that in post fix operator (– here acts as post ..we will first directly put the value of c1 and then only calculate…. and here the initial value of c1 was 11…so c2 will also be equal to 11.. but as soon as c2=11….now the post fix operator will come into action, and then make c1–=10

OUTPUT-:

the value of c1 is=11the value of c1 is=10the value of c2 is=11

Now, we will be diving into binary operator overloading.

Now let’s go towards binary operator overloading.

Same as unary operator.

i.e binary operator is also overloaded through help of 2 ways-

1) member operator function

2) friend function

And, binary operator overloading through member function takes 1 argument

Whereas, the binary operator overloading through friend function takes 2 arguments.

In the previous case, it was 0 and 1 argument respectively.

The basic syntax for doing these things is as follows.

Class class_name

{

Private:

//data members

Public:

//other member functions

Return_type operator operator_symbol(one arg);

};

Return_type class name::operator operator_symbol(one argument)

{

Body of the function

}

Q) Write a program showing the overloading of binary operator with the help of a member operator function.

And its output will come as follows.

Let’s discuss about that above program.

Before that, let me clear the theme of the above program.

It is stated as follows.

In case of binary operator overloading through member operator function, left hand side of the operand is used to invoke the member operator function whereas the right hand side of the operand is passed as an argument, during calling.

Left hand=invoke

right hand=passed

in c3=c1+c2, left hand ie c1=invoke, c2=passed.

The program explanation is as follows.

As per the question, we are being asked to overload the binary operator with the help of member operator function.

And we see that, we have declared a member operator function for operator overloading as

Money operator +(Money);

Money operator –(Money);

After that, we need to define them.

We prefer to define them outside of the class in this question. But you can also define them inside.

Now, we went of writing the calculation code inside those functions for addition and subtraction as discussed in earlier blogs.

They are being called from int main() as-:

M3=M1.operator +(M2)

Here M1 will store the value of paisa whereas M2 will help to store the value of M.paisa.

Now, through friend function.

The general syntax to overload binary operators through friend function is.

Class class_name

{

Private:

//data members

Public:

//other member functions

Friend return_type operator_symbol(two arguments);;

};

Return_type operator operator_symbol(2 args)

{

Body

}

Q) Write an example program showing the overloading of binary operators through non member operator functions i.e friend functions.

Its output will come as follows.

Its explanation is as follows.

Its working is exactly same as above….exception is that a friend function is used here….nothing special except friend function has been actually done here.

Mandatory use of friend function while overloading binary operators-:

Let us consider the two statements-:

C2=c1+5;-expression first

C2=5+c1;-expression second

They are same? Aren’t they? It is what you must be thinking right now.

They may be same for an arithmetician but not for a programmer.

Expression first can be overloaded with the help of a member operator function as well as friend function. however, expression second can only be overloaded with the help of a friend function only.

Look at the second expression-: c2=5+c1…here left hand=5 right hand=c1.

Left hand is used to invoke the member operator function. right hand is passed as argument.

Lefthand.fxn(right hand);

But but but, here left hand=5=built in data type.

And we know that built in data type=fundamental datatype can’t invoke the member function.

Why?

Because they are not the objects of a class.

So, so so…as we can’t do it by a member function…therefore, we need a friend function right here..

And this is the case of mandatory use of friend function.

Q) Write a program to achieve the operations c2=c1+5 and c2=5+c1; where c1 and c2 are the objects of type complex.

its output comes as follows.

 

2 Comments

  1. what are the disadvantages of op.overloading?
    1) it increases the execution time of a program as things are done in compile time
    2)some operators can’t be overloaded like scope resolution,conditional,dot operators etc.
    3)friend fxns can’t be used to overload some operators like arrow operator, index operator etc
    hence!

  2. a easy program for operator overloading
    unary postfix/prefix-same qn as above
    #include
    using namespace std;
    class teatemperature
    {
    int teaCel;
    public:
    teatemperature()
    {
    teaCel=0;
    }
    teatemperature(int x)
    {
    teaCel=x;
    }
    int retCel()
    {
    return teaCel;
    }
    void operator ++()//gasheat
    {
    ++teaCel;

    }
    friend teatemperature operator –(teatemperature &t1);
    };
    teatemperature operator –(teatemperature &t1)
    {
    teatemperature temp;
    temp.teaCel=–t1.teaCel;
    return temp;
    }
    int main()
    {
    teatemperature t1(10);
    ++t1;
    cout<<"so required value of t1 is after 1 sec increment="<Reply

Leave a Reply

Your email address will not be published.


*