Overloading Operators

Operators such as + and * in C++ can be considered to be functions taking two arguments (these are often called binary operators). Because they are functions, they can be overloaded. This section shows why and how you can overload operators.

Adding Two Points Together

Points in the two-dimensional space of a graph can be added together by adding their coordinates. They can also be divided by a scalar (that is, a single number). For example, you calculate the average of two points by adding them together and dividing by 2. The result is a point that is midway between them in space. This shows how the average of two Point structures can be calculated, by defining add() and div() functions:

 Point add(Point p1, Point p2) { ...

Get C++ By Example: UnderC Learning Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.