Operator Overloading in C++ - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Operator Overloading in C++

Share This

Operator overloading is one of the most exciting features of object-oriented programming. It can transform complex, obscure program listings into intuitively obvious ones. For example, statements like d3.addobjects(d1, d2); or the similar but equally obscure d3 = d1.addobjects(d2); can be changed to the much more readable d3 = d1 + d2;


The rather forbidding term operator overloading refers to giving the normal C++ operators, such as +, *, <=, and +=, additional meanings when they are applied to user-defined data types.


Normally, a = b + c; works only with basic types such as int and float, and attempting to apply it when a, b, and c are objects of a user-defined class will cause complaints from the compiler. However, using overloading, you can make this statement legal even when a, b, and c are user-defined types.


#include <iostream> using namespace std; class Test { int longitude, latitude; public: Test() {} Test(int lg, int lt) { longitude = lg; latitude = lt; } void show() { cout << longitude << " "; cout << latitude << "\n"; } Test operator+(Test op2); Test operator()(int i, int j); }; Test Test::operator()(int i, int j) { longitude = i; latitude = j; return *this; } Test Test::operator+(Test op2) { Test temp; temp.longitude = op2.longitude + longitude; temp.latitude = op2.latitude + latitude; return temp; } int main() { Test ob1(10, 20), ob2(1, 1); ob1.show(); ob1(7, 8); ob1.show(); ob1 = ob2 + ob1(10, 10); ob1.show(); return 0; }




Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.