Can someone please explain, in beginner terms, how operator overloading works? I need to overload the “+” operator as a member function with chaining to an objects array. Ive read some things from google, and it seems to operates the same way as “+” does without being overloaded, so I’m really confused.
This is what I have so far for the declaration:
ALIST<t_type> & operator+(const t_type );
So I declared this inside my ALIST class in the public section. Is the “+” operator overloaded now, or is there more I need to do in this functions definition to make it overloaded?
Also, once it is finally overloaded, what can I now do with it? What was the point of overloading it?
Please explain in beginner terms please, thanks.
Here is an example for why.
Say you are implementing a class of special vectors. For instance a
Colorclass.Colors 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
Colors together: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).
Which means our
Coloradding code now becomesA pain to write out.
But of course, If we take the
Colorclass, and overwrite the add operator to do all of this for us, in our code we can just writeWith this defined in out
Colorclass definitionSince 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 traditionalvectoradd. I bet you could go your entire career not overriding operators and I dont think you would not be missing out on much.