Here is an example for why.
Say you are implementing a class of special vectors. For instance a Color
class.
Color
s are going to basically be vectors with 4 values, r,g,b,a.
Now we are writing a graphics engine and in our program we will often want to know what happens to a pixels when the light from two different sources act on a pixel we are evaulauting (as in a ray tracer). It would be convient for to define a + operator to evaulate what happens when the light from two different sources are added together.
If we didnt have an operator you might write in your code to add two Color
s together:
Color newColor = Color(
color1.r + color2.r,
color1.g + color2.g,
color1.b + color2.b,
color1.a + color2.a
);
Even worse, if you are working closely with the physics of the light you might find that colors dont add normally. They might for instance add according to some linear function e.g. f(a) = a^2 ... (light doesn't do this I don't think, its just a random example).
f(a) = a^2; f(b) = b^2
f(a + b) = ??
a = f(a)^.5; b = f(b)^.5
a + b = f(a)^.5 + f(b)^.5
f(a + b) = (f(a)^.5 + f(b)^.5)^2 *yada yada yada i'm terrible at math.
Which means our Color
adding code now becomes
Color newColor = Color(
pow(pow(color1.r, .5) + pow(color2.r, .5),2),
pow(pow(color1.g, .5) + pow(color2.g, .5),2),
pow(pow(color1.b, .5) + pow(color2.b, .5),2),
pow(pow(color1.a, .5) + pow(color2.a, .5),2),
);
A pain to write out.
But of course, If we take the Color
class, and overwrite the add operator to do all of this for us, in our code we can just write
Color color = color1 + color2;
With this defined in out Color
class definition
Color Color::operator+(const Color &rhs) const {
return Color(
pow(pow(this.r, .5) + pow(rhs.r, .5),2),
pow(pow(this.g, .5) + pow(rhs.g, .5),2),
pow(pow(this.b, .5) + pow(rhs.b, .5),2),
pow(pow(this.a, .5) + pow(rhs.a, .5),2)
);
}
Since our special adding code is in only one place, you can optimize it far better, and the code in the rest of your program becomes much more readable.
That one way to looks at it at least. In the past, I have prefered functions like addLights(color1, color2)
as this is easier to code, just as easy to read, and more readable since it is obvious it is not a traditional vector
add. I bet you could go your entire career not overriding operators and I dont think you would not be missing out on much.