© Mikael Olsson 2020
M. OlssonC++20 Quick Syntax Referencehttps://doi.org/10.1007/978-1-4842-5995-5_20

20. Operator Overloading

Mikael Olsson1 
(1)
Hammarland, Finland
 

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

In the following example, there is a class called MyNum with an integer field and a constructor for setting that field. The class also has a method that adds two MyNum objects and returns the result as a new object.
class MyNum
{
  int val;
 public:
  MyNum(int i) : val(i) {}
  MyNum add(const MyNum &a) const {
    return MyNum( val + a.val );
  }
}; ...

Get C++20 Quick Syntax Reference: A Pocket Guide to the Language, APIs, and Library 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.