English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Overloading Operators and Overloading Functions

C++ Allow overloading operators and overloading functions within a certain scope ofFunctionsAndOperatorsSpecify multiple definitions, respectively calledFunction OverloadingAndOperator Overloading.

Overloading Declaration refers to a declaration with the same name as a function or method that has already been declared within the same scope, but their parameter lists and definitions (implementations) are different.

When you call aOverloading FunctionsorOverloading OperatorsWhen making an overloading decision, the compiler determines the most appropriate definition by comparing the types of parameters you use with the types of parameters defined. The process of selecting the most appropriate overloaded function or overloaded operator is calledOverloading Decision.

C++ Function Overloading

Within the same scope, several functions with the same name and similar functionality can be declared, but the formal parameters (referring to the number, type, or order of the parameters) of these same-name functions must be different. You cannot overload functions solely by different return types.

The following example demonstrates a function with the same name. print() is used to output different data types:

#include <iostream>
using namespace std;
 
class printData
{
   public:
      void print(int i)
        cout << "The integer is: " << i << endl;
      }
 
      void print(double f)
        cout << "The floating-point number is: " << f << endl;
      }
 
      void print(char c[])
        cout << "The string is: " << c << endl;
      }
};
 
int main(void)
{
   printData pd;
 
   // Output integer
   pd.print(5);
   // Output floating-point number
   pd.print(500.263);
   // Output string
   char c[] = "Hello C++";
   pd.print(c);
 
   return 0;
}

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

The integer is: 5
The floating-point number is: 500.263
The string is: Hello C++

C++ operator overloading

You can redefine or overload most C++ Built-in operators. This way, you can use operators for custom types.

Overloaded operators are functions with special names, whose names are composed of the keyword operator followed by the operator symbol to be overloaded. Like other functions, overloaded operators have a return type and a parameter list.

Box operator+(const Box&);

Declare the addition operator to add two Box objects and return the final Box object. Most overloaded operators can be defined as regular non-member functions or as class member functions. If we define the above function as a non-member function of the class, then we need to pass two parameters for each operation, as shown below:

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

The following example uses member functions to demonstrate the concept of operator overloading. Here, the object is passed as a parameter, and the object's properties are accessed using this operators for access, as shown below:

#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, used 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;     // Width
      double height;      // Height
};
// The main function of the program
int main( )
{
   Box Box1;                // Declare Box1, type Box
   Box Box2;                // Declare Box2, type Box
   Box Box3;                // Declare Box3, type Box
   double volume = 0.0;     // Store the volume in this variable
 
   // Box1 Detailed description
   Box1.setLength(6.0); 
   Box1.setBreadth(7.0); 
   Box1.setHeight(5.0);
 
   // Box2 Detailed description
   Box2.setLength(12.0); 
   Box2.setBreadth(13.0); 
   Box2.setHeight(10.0);
 
   // Box1 volume
   volume = Box1.getVolume();
   cout << "Box1Volume: " << volume << endl;
 
   // Box2 volume
   volume = Box2.getVolume();
   cout << "Box2Volume: " << volume << endl;
 
   // Add two objects to get Box3
   Box3 = Box1 + Box2;
 
   // Box3 volume
   volume = Box3.getVolume();
   cout << "Box3Volume: " << volume << endl;
 
   return 0;
}

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

Box1Volume: 210
Box2Volume: 1560
Box3Volume: 5400

Overloadable operators/Non-overloadable operators

The following is a list of overloadable operators:

Binary arithmetic operators+ (addition),-(subtraction),*(multiplication),/(division), %(modulo)
Relational operators==(equal), != (not equal), < (less than), > (greater than), <= (less than or equal), >= (greater than or equal)
Logical operators||(logical or), &&(logical and), !(logical not)
Unary operators+ (positive),-(negative),*(pointer), &(address-of)
Increment and decrement operators++(increment),--(decrement)
Bitwise operators| (bitwise or), & (bitwise and), ~ (bitwise not), ^ (bitwise exclusive or), << (left shift), >> (right shift)
Assignment operators=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
Memory allocation and deallocationnew, delete, new[], delete[]
Other operators()(function call),-(member access), (comma), (subscript)[

The following is a list of non-overloadable operators:

  • .: Member Access Operator

  • .*, ->*=: Member Pointer Access Operator

  • ::: Scope Operator

  • sizeof: Length Operator

  • ?:: Conditional Operator

  • #: Preprocessor Symbol

Operator Overloading Examples

The following provides various operator overloading examples to help you better understand the concept of overloading.

NumberOperators and Examples
1Unary Operator Overloading
2Binary Operator Overloading
3Relational Operator Overloading
4Input/Output Operator Overloading
5 ++ And -- Operator Overloading
6Assignment Operator Overloading
7Function Call Operator () Overloading
8Subscript Operator [] Overloading
9Class Member Access Operator -> Overloading