C++ allows you to define functions for operators, this is called operator overloading.
Now why would you need to do that? Well, consider the Circle class we defined earlier. Let’s say I needed to compare two circles to see which one was larger, normally I’d write something like:
if(c1 > c2) {
// do something because c1 is the bigger one
}
The problem is, C++ has know way of knowing how to evaluate the Circle class and it’s objects. Operator overloading allows us to do that very thing.
Common operators we can overload include:
+, -, *, /, %, ^,&, <, >, <=, >=, ==, !=, <<, >>, and more. See table 14.1 for more examples.
Now we will create these as functions. And while we can reference them via their function names, we’ll usually use the operator since it is easier. Consider the following where we see how the class string uses overloaded operators to make working with the strings easier.
string s1("Cali.");
string s2("LA");
// this is the same as
cout << s2 + s1 << endl;
cout << (s1 < s2) << endl;
// what this is...
cout << operator+(s2, s1) << endl;
cout << operator<(s1, s2) << endl;
To create our operator overloading, we would go into our class file. First in our header we’d add something like:
bool operator<(Circle c2);
Then in our Circle.cpp file we’d add:
bool Circle::operator<(Circle c2) {
return radius < c2.getRadius();
}
Operator Overloading was originally found on Access 2 Learn
One Comment
Comments are closed.