Skip to main content
Engineering LibreTexts

14.1: Overview

  • Page ID
    29118
  • What is overloading in C++?​

    Creating two or more objects that have the same name but are different in how they operate is known as overloading.

    In C++, we can overload:

    • Operators
    • Methods - often referred to as function overloading

    Types of overloading

    overloading.png

    Operator Overloading in C++

    We will discuss operator overloading first, then in the next section we will discuss function overloading.

    In C++, we can make operators to work for user defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading.

    For example, we can overload an operator ‘+’ in a class like String so that we can concatenate two strings by just using + as in the following example code snippet

    String firstName = "Pat";
    String lastName = "McClanahan";
    String fullName;
    
    // The + operator understands it is working on Strings
    // so it concatenates them instead of attempting to add them
    fullName = firstName + lastName
    

    Other example classes where arithmetic operators may be overloaded are Complex Number, Fractional Number, Big Integer, etc.

    What is the difference between operator functions and normal functions?

    Operators methods are same as normal methods. The only differences are, name of an operator function is always operator keyword followed by symbol of operator and operator functions are called when the corresponding operator is used.

    Following is an example of global operator function.

    // CPP program to illustrate
    // Operator Overloading
    #include<iostream>
    using namespace std;
    
    class Complex {
        private:
            int real, imag;
        public:
            Complex(int r = 0, int i =0)
            {
                real = r; imag = i;
            }
            
            // This is automatically called when '+' is used with
            // between two Complex objects
            Complex operator + (Complex const &obj)
            {
                Complex res;
                res.real = real + obj.real;
                res.imag = imag + obj.imag;
                return res;
            }
            void print()
            {
                cout << real << " + i" << imag << endl;
            }
    };
    
    
    int main()
    {
        Complex c1(10, 5), c2(2, 4);
        Complex c3 = c1 + c2; // An example call to "operator+"
        c3.print();
    }
    
    

    In this code we see the statement "Complex operator + (Complex const &obj)" - this tells C++ that this method is dealing with one of the operators, in this case the + operator. This allows the programmer to overload the operator to perform in a specific way for the class the method is defined in. Don't worry if you do not understand complex number...the point here is that we are overloading the + operator to do something different for our class named Complex.

    In case you are interested, the output from the sample code is:

    12 + i9

    Can we overload all operators?

    Almost all operators can be overloaded except few. Following is the list of operators that cannot be overloaded.

       . (dot) 
       :: 
       ?: 
       sizeof 

    Why can’t . (dot), ::, ?: and sizeof be overloaded?
    See this for answers from Stroustrup (the creator of C++) himself.

    Important points about operator overloading
    1) For operator overloading to work, at least one of the operands must be a user defined class object.

    2) Assignment Operator: Compiler automatically creates a default assignment operator with every class. The default assignment operator does assign all members of right side to the left side and works fine most of the cases (this behavior is same as copy constructor). See this for more details.

    3) Conversion Operator: We can also write conversion operators that can be used to convert one type to another type.

    #include <iostream>
    using namespace std;
    class Fraction
    {
        private:
            int num, den;
        public:
            Fraction(int n, int d)
            {
                num = n; den = d;
            }
    
    
            // conversion operator: return float value of fraction
            operator float() const
            {
                return float(num) / float(den);
            }
    };
    
    
    int main() {
        Fraction frac(2, 5);
        float val = frac;
        cout << val;
        return 0;
    }
    
    

    When the code executes the statement float val = frac; we create an instance of the conversion operator, which calls the float() method. This method takes the two integer values, num and den, which were created and assigned values what we create an instance of the Fraction class: Fraction frac(2,5); and using the system float conversion to convert them to floating point values and performs the division. This overloading does a different conversion than the system conversion method which simply changes an integer value into a floating valiing.

    The output is the result of a simple division:

    0.4

    Adapted from:
    "What is overloading in C++?​" by Zaid Kesaranieducative is licensed under CC BY-SA 4.0
    "Operator Overloading in C++" by Shun Xian CaiGeeks for Geeks is licensed under CC BY-SA 4.0