Search⌘ K

Operator Overloading

Explore operator overloading in C++ to customize operator behavior for your own data types. Learn key rules, how to overload assignment operators for copy and move semantics, and how friend functions support operations between objects.

Definition #

C++ allows us to define the behavior of operators for our own data types. This is known as operator overloading.

Operators vary in nature and therefore, require different operands. The number of operands for a particular operator depends on:

  1. the kind of operator (infix, prefix, etc.)

  2. whether the operator is a method or function.

struct Account{
  Account& operator += (double b){
    balance += b;
    return *this; }....
};

...
Account a;
a += 100.0;

We have already encountered function overloading. If the function is inside a class, it must be declared as a friend and all its arguments must be provided.

Rules #

To achieve perfect operator overloading, there is a large set of rules we have to follow. Here are some of the important ones. ...