Easy Tutorial
❮ Relational Operators Overloading Cpp Examples Swapping ❯

C++ Operator Overloading and Function Overloading

C++ allows specifying more than one definition for a function and an operator in the same scope, which is called function overloading and operator overloading respectively.

An overloaded declaration is a declaration that had been declared with the same name as a previously declared function or method in the same scope, except that both declarations have different parameter lists and definitions (implementations).

When you call an overloaded function or overloaded operator, the compiler determines the most appropriate definition to use by comparing the argument types you have used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution.

Function Overloading in C++

Within the same scope, you can declare several functions with similar functionality but different formal parameters (different numbers, types, or orders of parameters). You cannot overload functions based solely on different return types.

In the following example, the function print() is used to print different data types:

Example

#include <iostream>
using namespace std;

class printData
{
   public:
      void print(int i) {
        cout << "Integer: " << i << endl;
      }

      void print(double f) {
        cout << "Float: " << f << endl;
      }

      void print(char c[]) {
        cout << "String: " << c << endl;
      }
};

int main(void)
{
   printData pd;

   // Print integer
   pd.print(5);
   // Print float
   pd.print(500.263);
   // Print string
   char c[] = "Hello C++";
   pd.print(c);

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Integer: 5
Float: 500.263
String: Hello C++

Operator Overloading in C++

You can redefine or overload most of the built-in operators available in C++. Thus, you can use operators with user-defined types.

An overloaded operator is a function with a special name, where the function name starts with the keyword operator followed by the operator symbol to be overloaded. Like any other function, an overloaded operator has a return type and a parameter list.

Box operator+(const Box&);

This declaration states that the addition operator is used to add two Box objects, returning the resultant Box object. Most overloaded operators can be defined as ordinary non-member functions or as class member functions. If we define the above function as a non-member function, we need to pass two parameters for each operation, as shown below:

Box operator+(const Box&, const Box&);

The following example demonstrates the concept of operator overloading using member functions. Here, the object is passed as an argument, and its attributes are accessed using the this operator, as shown below:

Example

#include <iostream>
using namespace std;

class Box
{
   public:
      double getVolume(void)
      {
         return length * breadth * height;
      }
      void setLength( double len )
      {
          length = len;
      }

      void setBreadth( double bre )
      {
          breadth = bre;
      }

      void setHeight( double hei )
      {
          height = hei;
      }
      // Overload + operator to add two Box objects
      Box operator+(const Box& b)
      {
         Box box;
         box.length = this->length + b.length;
         box.breadth = this->breadth + b.breadth;
         box.height = this->height + b.height;
         return box;
      }
   private:
      double length;      // Length
      double breadth;     // Breadth
      double height;      // Height
};
class Box {
   double height;  // height
};
// Main function of the program
int main() {
   Box Box1;  // Declare Box1, of type Box
   Box Box2;  // Declare Box2, of type Box
   Box Box3;  // Declare Box3, of type Box
   double volume = 0.0;  // Store the volume in this variable

   // Details of Box1
   Box1.setLength(6.0); 
   Box1.setBreadth(7.0); 
   Box1.setHeight(5.0);

   // Details of Box2
   Box2.setLength(12.0); 
   Box2.setBreadth(13.0); 
   Box2.setHeight(10.0);

   // Volume of Box1
   volume = Box1.getVolume();
   cout << "Volume of Box1 : " << volume << endl;

   // Volume of Box2
   volume = Box2.getVolume();
   cout << "Volume of Box2 : " << volume << endl;

   // Add two objects to get Box3
   Box3 = Box1 + Box2;

   // Volume of Box3
   volume = Box3.getVolume();
   cout << "Volume of Box3 : " << volume << endl;

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

Overloadable/Non-overloadable Operators

Here is the list of operators that can be overloaded:

| Binary Arithmetic Operators | + (addition), - (subtraction), * (multiplication), / (division), % (modulus) | | Relational Operators | == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to) | | Logical Operators | || (logical OR), && (logical AND), ! (logical NOT) | | Unary Operators | + (positive), - (negative), * (pointer), & (address-of) | | Increment/Decrement Operators | ++ (increment), -- (decrement) | | Bitwise Operators | | (bitwise OR), & (bitwise AND), ~ (bitwise NOT), ^ (bitwise XOR), << (left shift), >> (right shift) | | Assignment Operators | =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>= | | Memory Allocation and Deallocation | new, delete, new[], delete[] | | Other Operators | () (function call), -> (member access), , (comma), [] (subscript) |

Here is the list of operators that cannot be overloaded:

Operator Overloading Examples

Below are various examples of operator overloading to help you better understand the concept of overloading.

No. Operator and Example
1 Unary Operators Overloading
2 Binary Operators Overloading
3 Relational Operators Overloading
4 Input/Output Operators Overloading
5 ++ and -- Operators Overloading
6 Assignment Operators Overloading
7 Function Call Operator () Overloading
8 Subscript Operator [] Overloading
9 Class Member Access Operator -> Overloading
❮ Relational Operators Overloading Cpp Examples Swapping ❯