C++: Operator Overloading

One of the beautiful feature of ‘C++’ is its ability to support Operator Overloading. ‘C++’ Operator Overloading allows to change the behavior of operators when using them with ‘C++’ class objects.

One of the best example of Operator Overloading is ‘+’ operator. Usually ‘+’ operator will add two integer operands and produce an integer result. For string class, ‘+’ operator will be used to concatenate two strings. This is achieved by overloading ‘+’ operator for string class.

Operator Overloading provides the flexibility to write more meaningful and readable code.

‘C++’ allows to overload almost all the operators; except Scope Resolution Operator (“::”)Member Selection Operator (“.”) and (“.*”).

The syntax of operator overloading is:

<return type> operator <op>(<arguments>);

Here operator is the keyword indicates this is the operator overloading function.

  • <op> is the actual operator we are going to overload. It will be +, -, *, or any other operator ‘C++’ allows to overload.
  • <return type> is the return type the operator overloading function returns.
  • <arguments> is zero or more arguments. Number of arguments depends on the type of the operator you are going to overload.

Let us take a simple example.

// sample.cpp

#include <iostream>
#include <string.h>

using namespace std;

class Sample
{
private:
   char m_str[1024];

public:
   Sample(const char *str)
   {
      strcpy(m_str, str);
   }

   Sample operator +(Sample obj)
   {
      strcat(m_str, obj.getstr());
      
      return Sample(m_str);
   }

   char *getstr()
   {
      return m_str;
   }
};

// main
//
int main()
{
   Sample sample("Hello!");

   cout << (sample + " World!").getstr() << endl;

   return 0;
}

In this example, we have create a Sample class which holds a string. We have overloaded ‘+’ operator to merge the string with the string inside the Sample class.

Compile and run the program to see the results.

// Malin

Leave a Reply