in C++ are things such as +
. Now, if one has two variables of type int
(which means they both represent integers), it's pretty clear how the "+" operator should work on them. It should add them, and return the result. Thus, the code fragment
int foo, bar, baz; //Declare integer variables "foo", "bar", and "baz"
foo = 5; //Set foo to 5
bar =6; //Set bar to 6
baz = foo + bar;
results in the variable baz
having a value of 5+6, or 11.
But what if you want to add something other than one of the fundamental types. What if you have two objects of class Box? How do you add two boxes? It depends on the specific requirements of your program.
And, without operator overloading, one would have to declare, within the Box class a function such as this:
Box Add(Box otherbox);
and use it like so
box3 = box2.Add(box1);
Now, with operator overloading, we can merely declare a function called operator+ to overload the "+" operator. The declaration looks similar to the one above(and the code within the function would be identical):
Box operator+(Box otherbox);
but now this is a valid statement
box3 = box2 + box1;
The advantage to operator overloading is that it makes code much more readable. However, people who dislike it claim that it tends to make code more cryptic.