C++ overloading is the mechanism by which the language
standard operators are used for customized operations of the
classes. For example if we are trying to write a string class,
we would very simply ask for "+" operator to handle
string concatenation, "-" for removing one part of
string from another etc.,
This will put the users at ease. They need not
worry about the internal handling of string operations or
memory allocations. Instead they can start writing cleaner
code concentrating only on the application functionality. Code
Reusability becomes easier. Though the overloaded operators
are very cleaner to use, the internals could be a little
dirty. That is what, is the only problem/drawback with c++
overloading.
The developer of a class with such overloaded
operators has to go through a painful set of coding to ensure
the users are comfortable ( though at the developer's cost).
All the operators can be overloaded except ., ?:,
sizeof, ::,
.* . Now let us see an example of using the "+"
operator.
//C++
overloading sample
class
MyString
{
public:
char member1[100];
void operator +(MyString val)
{
strcat(member1, val.member1);
}
};
The other intricacies of initializing the class, destructors
etc., are left out for the sake of simplicity and readability.
Similar to the above example of c++ overloading,
we can overload all other operators (except some) to give them
a meaningful usage for the classes.
Usually unary operators may not need a parameter
(or may need one at the most) and binary operators may need at least
one parameter to be passed inside. This is how most of
the times the logic on overloading works( and may differ too
sometimes).
Also some people will use techniques of passing a parameter
to differentiate between a pre fix and post fix
operators.
The stream
operators << and << need a different type of
treatment. Though these kind of techniques make the life of
the developer difficult, it is the user who is going to be benefited
the most.