Menu

Overloading in C++

  • Overloading in C++ allows specifying more than one definition for a function name or an operator in the same scope is called function overloading and operator overloading respectively.
  • An overloaded function can have multiple definitions for the same function name in the same scope.
  • The definition of the function must differ from each other by the types and/or the number of arguments in the argument list.
  • Overloading occurs when the same operator or function name is used with different signatures.
  • Both operators and functions can be overloaded.
  • Operator overloading refers to giving normal C++ operators such as +,* and <= and so on, an additional meaning when they applied to user-defined data types.

C++ operators that can be overloaded

+ - * / % ^ & I
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>==
<<== == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]            

Operators that cannot be overloaded

. .* :: ?= % sizeof & I

Syntax

      returnType operator*(parameters);
  • 'returnType' may be whatever the operator returns (Including a reference to the object of the operand).
  • 'Operator' symbol may be any valid operator allowed by the language compiler.

Types of operators

  1. Unary Operators (prefix (!,&,^,......), postfix (++, --, ......))
  2. Binary operators(+, <, = ......)

Operators attached to single operand

  • Eg: -a, +a, --a, a--, ++a, a++,.......

Operators attached to two operands

  • Eg: a-b, a+b, a*b, a/b, a%b, a>b, a>=b, a<b, a<=b, a==b

Operators that cannot be overloaded due to safety reasons

  1. Member selection "." operator
  2. Member dereference operator
  3. Exponential "**" Operator
  4. User-defined Operators
  5. Operator precedence rule
    #include
    using namespace std;
    class sum{
      int num1;
      int num2;
      int sum;
      private:
      void inputdata();
      void processdata();
      void outputdata();
    }
    void sum::inputdata(){
      cout<<"enter the first and the second number:";
      cin>>a>>b;
    }
    void sum::processdata(){
      sum=a+b;
    }
    void sum::outputdata(){
      cout<"The sum of two numbers is "<<sum;
    }

    main(){
      sum obj;
      obj.inputdata();
      obj.processdata();
      obj.outputdata();
    }

Output

     Enter the first and second number:4 4 
     The sum of two numbers is 8