CHAPTER 20

image

Operator Overloading

Operator overloading allows operators to be redefined and used where one or both of the operands are of a user-defined class. When done correctly, this can simplify the code and make user-defined types as easy to use as the primitive types.

Operator Overloading Example

In the example below there is a class called MyNum with an integer field and a constructor for setting that field. The class also has an addition method that adds two MyNum objects together and returns the result as a new object.

class MyNum{ public:  int val;  MyNum(int i) : val(i) {}  MyNum add(MyNum &a)  { return MyNum( val + a.val ); }}

Two ...

Get C++ 14 Quick Syntax Reference, Second 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.