Login    New User    Forgot Password    Help      

Operator Overloading in C++

GO TO INDEX

Operator Overloading in C++

In C++ the overloading principle applies not only to functions, but to operators too. That is, of operators can be extended to work not just with built-in types but also classes. A programmer can provide his or her own operator to a class by overloading the built-in operator to perform some specific computation when the operator is used on objects of that class. Is operator overloading really useful in real world implementations? It certainlly can be, making it very easy to write code that feels natural (we'll see some examples soon). On the other hand, operator overloading, like any advanced C++ feature, makes the language more complicated. In addition, operators tend to have very specific meaning, and most programmers don't expect operators to do a lot of work, so overloading Operators can be abused to make code unreadable. But we won't do that.

OAn Example of Operator Overloading

Complex a(1.2,1.3);     //this class is used to represent complex numbers  
Complex b(2.1,3);       //notice the construction taking 2 parameters for the real and imaginary part  
Complex c = a+b;        //for this to work the addition operator must be overloaded  
The addition without having overloaded operator + could look like this:
Complex c = a.Add(b);  
This piece of code is not as readable as the first example though--we're dealing with numbers, so doing addition should be natural. (In contrast to cases when programmers abuse this technique, when the concept represented by the class is not related to the operator--ike using + and - to add and remove elements from a data structure. In this cases operator overloading is a bad idea, creating confusion.)

GO TO INDEX