Saturday, September 5, 2009

Operator Overloading

It is a wonderful feature of C++ through which we can provide different meaning to the operators such as +,-,=,== etc. Operators have different implementation according to requirement.

As you know that operator can be used in mathematical expressions:

int i = j + 18; float x = y*1.5;

Now it would be great if we could use such kind of operations with Objects. For example, If should be able to join or concatenate two Strings by using + operator. Is it possible? Yes you can! That's what Operator Overloading for.

String first_name = "Amitabh";
String last_name = "Bachchan";

Now if we want to concatenate both String into one. C++ should allow to do it. like :

String full_name = first_name+last_name;

Its absolutely fine. It can be done successfully.

But, What about user-defined classes? Can this concept is applicable to them also?

Let us take two user-defined date objects;

Class Time {
int hours;
int minutes;
int seconds;
. . . .
. . . .
Create objects of class Time :-
. . . .
Time time1, time2;
Time time3 = time1 + time2; //(Its 100% valid.)
time3++; // (this too...)
. . . .
. . . .
So, we can say that objective of Operator overloading is to provide experience of primitive data type with user defined datatype. Like this :

Primitive Data type User Defined Data type
int num1,num2;Time time1,time2;
int num3=num1+num2; Time time3=time1+time2;

Some Points to REMEMBER : -

  • New operators can not be created. Functionality of built-in operators can be modified.
  • Not all the operators can be overloaded.There are few which can not be overloaded.

In C++, about 40 predefined operators can be overloaded. The operator which can not be overloaded are as follows :

::, . , .*, sizeof , ?:

We can not overload preprocessing symbols like # and ###.

To be continued.....