Operator Overloading

C++ allows us to overload operators. Let's find out how.

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.

  • We cannot change the precedence of an operator. The compiler computes all operators in order of precedence. We cannot alter this order. Hence, whatever operation our operator performs, it will be computed after the operator with higher precedence.

  • Derived classes inherit all the operators of their base classes except the assignment operator. Each class needs to overload the = operator.

  • All operators other than the function call operator cannot have default arguments.

  • Operators can be called explicitly. A benefit of overloading an operator is that it can be used directly with its operands. However, the compiler may cause some implicit conversion in this process. We can make explicit calls to the overloaded operator in the following format: a.operator += (b).

Example #

Get hands-on with 1200+ tech skills courses.