Are There Any Uses For Operator Overloading in C++?

Status
Not open for further replies.

theopfor

In Runtime
Messages
173
Location
Right behind you
I am learning operator overloading in C++ right now. Some of it is a little confusing, but I could probably fix that in some cross-referencing. The webpage I am using (9.2 — Overloading the arithmetic operators « Learn C++), doesn't seem to give reasonable examples of the uses for operator overloading for arithmetic operators. I am continuing to read the chapter.

Are there any uses for operator overloading in C++?
 
The typical example in c++ is normally a "money" class if I recall with dollars and cents. It's not terribly useful in itself, but it's useful just to illustrate the technique and the reasons. The operators only work on the primitive data types. Any abstract data types you create would require you overload these operators to use them to compare or do whatever with your data.

Since you're wondering where operator overloading is really useful though, I would say strings are the best example. Say you want to know when 2 strings are equal. What do you do? You use the compare() method or some other member of the string class. If you overload the = sign though in place of your compare function, then you can use it to compare strings.

This might not seem like much, but there's a couple places where it could come in handy. For example, sorting algorithms are all written using integers as examples. You'd have to modify these examples if you wanted to use them to sort strings in your code. But if you overload things like <, =, and > for strings, then you might be able to quickly implement different sorting methods in your code with little work on your end.

So yeah, I can at least suggest overloading when you think it'll save you some time translating other big tracks of code that you might want to use.
 
Status
Not open for further replies.
Back
Top Bottom