Operator overloading

S

sarathy

Hi,
I have few doubts in operator overloading. Overloading is fine
for operators such as +, * , - , / .......
But why would anyone overload operators [ ] ( ) -> I dont see any real
use when these are overloaded. Particularly the ( ) operator.

What ( ) achieves can be acheived by normal functions and constructors
itself. Then why an overload ?

Please do clarify,
Sarathy
 
J

Jakob Bieling

sarathy said:
But why would anyone overload operators [ ]

Have a look at the vector class. If you could not overload operator
[], you would have to call a member function as in 'myvec.get_element
(idx);', instead of simply doing 'myvec [idx];'. The latter looks
already familiar and thus makes your code more readable.

It is commonly used in functor class. So you can use the familiar
function call syntax and your functor will take the appropriate action.
It can also be used in a matrix class. If you want to retrieve the
element in the first row and the first column, the operator () could be
implemented to take two arguments, one for the row, one for the column.

Have a look at the smart pointer classes in boost or even the
auto_ptr in Standard C++. They overload this operator to make an object
behave very similar to a regular pointer.
What ( ) achieves can be acheived by normal functions and constructors
itself. Then why an overload ?

Because it makes your code easier to read. You can also achieve the
same thing an operator+ does using regular functions. But writing "k =
add (i, j);" is much less readable than "k = i + j;". The same argument
applies to operator [], (), -> and actually all others.

Always carefully think about which operators you want to overload
and how. It is no use to overload operators, just because you have the
ability to do so, but giving them completely different meanings.

hth
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,069
Latest member
SimplyleanKetoReviews

Latest Threads

Top