function and operator overloading

i'm fairly new to c++ and i was curious; why have function and operator overloading. i'm finding lots of things about the mechanics and syntax of it all but no one has yet said why.

if i'm going to have two different variables or functions why call them the same name?
Look at something like pow:

1
2
3
     double pow (double base     , double exponent);
      float pow (float base      , float exponent);
long double pow (long double base, long double exponent);


These functions all do the same thing, but they might need to do it a bit differently for different types of arguments. Hence, function overloading.

Operator overloading is also another form syntactic sugar; it lets you do things like:

1
2
std::string one = "one", two = "two";
std::string onetwo = one + two;


Otherwise you would have to use something like append(), which looks ugly and hard to read.
Overloading is for functions; not for variables.

C does not have overloading. For example, C has functions round, roundf, and roundl. They differ only by the type of parameter. Suppose that you have code that uses floats and rounds them. Then you have to replace float with long double for some reason. Now you have to replace every roundf with roundl.

Same program in C++. Previously, you did call round and the compiler did link to the float-version of round. After code change compiler does link to the long double version without you having to change any call to round.

"Three names isn't so bad and they are explicit."
Sure. Lets take template <class T> const T& max (const T& a, const T& b);
Would you really want to invent a unique name for max for each comparable type?


Operators are syntactic sugar. You can write: cout << 42;
That is actually: cout.operator<<( 42 );
Of course the cout could have members with more descriptive name, say printT, so you could write cout.printi( 42 );

However, I can now write:
1
2
Foo x;
cout << x;

and you might guess that it prints the x. I cannot change cout, but I can provide an overloaded << for class Foo. However, in non-operator non-overloading world you could not write cout.printFoo( x );
Topic archived. No new replies allowed.