July 2013
Intermediate to advanced
124 pages
1h 42m
English
CHAPTER 20
![]()
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 ); }}
Read now
Unlock full access