Skip to main content
Engineering LibreTexts

4.11: Operator Overloading

  • Page ID
    29043
  • What is Overloading?

    C++ allows the specification of more than one definition for an operator in the same scope, which is called operator overloading.

    An overloaded declaration is a declaration that is within the same scope and with the same name as a previous declaration, except that both declarations have different arguments and obviously different definition (implementation).

    When an overloaded operator is called, the compiler determines the most appropriate definition to use, by comparing the argument types that have used to call the operator with the parameter types specified in the definitions. 

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

    Overloaded operators are functions with special names: the keyword "operator" followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.

    Example:

    #include <iostream>
    using namespace std;
    
    // Define a Class, a private variable: myVal, and 3 Class Methods: MyClass() - this is the creator; operator ++();
    // and Showem()
    class MyClass
    {
       private:
          int myVal;
    
       public:
           MyClass()
           { 
               myVal = 99;
           } 
    
           void operator ++() 
           { 
              myVal = myVal + 5; 
           }
    
           void Showem() 
           { 
               cout<<"Value is: "<< myVal << endl; 
           }
    };
    
    
    int main()
    {   // Create an instance of Class MyClass
        MyClass myInstance;
    
        // calls our overloaded ++() operator function INSTEAD of the system ++ operator
        // which adds 5 to the value of myVal
        ++myInstance;    
        // Print out the new value of myVal
        myInstance.Showem();
    
        return 0;
    }

    Output:

    Value is: 104
    

    Overloading allows you to create your own operators that behave in ways different than what C++ operators do, which provides a huge amount of flexibility in your code.