Monday, March 24, 2014

Operator Overloading

I've  been learning something really cool.

Basically, C++ has some built in operators.  These can manipulate the data in the program.  For instance, there are mathematical operators.  For instance, if I tell my program:

5 + 5

It will return 10.

But what if I create my own class? 

Take, for instance, a class for vectors.  Vectors have direction and magnitude.  What they are and how they work can be read here.  Vectors can be simulated with a set of 3 coordinates, similar to a point on a 3D graph, which shows where the vector terminates and from which its magnitude can be calculated.

So, if the vector has three coordinates, how can I tell the program to add two together?  I would have to write a function telling the program to add the corresponding coordinates from each vector (AX + BX, AY + BY, AZ + BZ).  This works alright, but the syntax behind it can be confusing, or at best, hard to read.  Perhaps I write a method called "add" to add vectorA and vectorB together.  To implement this into the program, I might have to write something like this:

vectorC = vectorA.add(vectorB);

Using operator overloading, I can now make my vector class work just like built in data types in C++.  If I overload the + operator, I can tell the program that when I use + with two vectors, it means to add each corresponding coordinate.  Now, to have the program do what I want it to do, all I have to do is type:

vectorC = vectorA + vectorB;

It seems trivial, but it makes things a lot easier to read and understand when I'm creating my own data types.

1 comment: