Classes (II) : Overloading Operators
Classes (II) : Overloading Operators
Overloading operators
Classes, essentially, define new types to be used in C++ code. And types in C++ not only interact
with code by means of constructions and assignments. They also interact by means of operators.
For example, take the following operation on fundamental types:
1
2
int a, b, c;
a = b + c;
Here, different variables of a fundamental type (int) are applied the addition operator, and then
the assignment operator. For a fundamental arithmetic type, the meaning of such operations is
generally obvious and unambiguous, but it may not be so for certain class types. For example:
1
2
3
4
5
struct myclass {
string product;
float price;
} a, b, c;
a = b + c;
Here, it is not obvious what the result of the addition operation on b and c does. In fact, this code
alone would cause a compilation error, since the type myclass has no defined behavior for
additions. However, C++ allows most operators to be overloaded so that their behavior can be
defined for just about any type, including classes. Here is a list of all the operators that can be
overloaded:
Overloadable operators
+ - * / = < > += -= *= /= << >>
<<= >>= == != <= >= ++ -- % & ^ ! |
~ &= ^= |= && || %= [] () , ->* -> new
delete new[] delete[]
Operators are overloaded by means of operator functions, which are regular functions with
special names: their name begins by the operator keyword followed by the operator sign that is
overloaded. The syntax is:
type operator sign (parameters) { /*... body ...*/ }
For example, cartesian vectors are sets of two coordinates: x and y. The addition operation of
two cartesian vectorsis defined as the addition both x coordinates together, and
both y coordinates together. For example, adding thecartesian vectors (3,1) and (1,2) together
would result in (3+1,1+2) = (4,3). This could be implemented in C++ with the following
code:
1
2
// overloading operators example
#include <iostream>
4,3
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using namespace std;
class CVector {
public:
int x,y;
CVector () {};
CVector (int a,int b) : x(a), y(b) {}
CVector operator + (const CVector&);
};
CVector CVector::operator+ (const CVector&
param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return temp;
}
int main () {
CVector foo (3,1);
CVector bar (1,2);
CVector result;
result = foo + bar;
cout << result.x << ',' << result.y <<
'\n';
return 0;
}
If confused about so many appearances of CVector, consider that some of them refer to the class
name (i.e., the type) CVector and some others are functions with that name (i.e., constructors,
which must have the same name as the class). For example:
1
2
CVector (int, int) : x(a), y(b) {} // function name CVector (constructor)
CVector operator+ (const CVector&); // function that returns a CVector