Operator Overloading In C++

Operator Overloading

Operator Overloading In C++

Operator Overlolading

tags : C++ Object Oriented Programming

Abstract

Operator overloading is one of the important feature in C++ language.Operator overloading is complie time polymorphism in which we give a special meaning to an operator.Most important is that when an operator is overloaded it's original meaning is not lost.

Scope Of Article

  • This article defines operator overloading and explains it using examples and code in a very intuitive which helps reader to learn concept in very easy way.

Contents


Definition

  • Operator overloading is a compile time polymorphism(ability to make more than one forms or one name multiple forms).
  • The mechanism of giving special meanings to an operator without loosing original identity is known as Operator Overloading
  • Operators are overloaded by using special keyword operator which describes the task. below syntax have been discussed.
  • Operator Function must be either member functions(non-static) or friend functions. A basic difference difference between them is that friend function will have only one argument for unary operator and two argument for binary operators. while member function has no arguments for every unary operators and only one for binary operators, This is because the object used to invoke the member function is passed implicitly and therefore is available for the member function.where in case of friend function , Arguments may be passed either by value or by reference.

    Steps

  • Create a class that defines the data type that is to be used in the overloading operation.
  • Declare the operator function operator op() int the public part of the class.It may be either a memeber function or a friend function.

Syntax For Overloading Operator

   return-type classname :: operator op(arglist)
   {
        // Function body
   }

where....

  • return-type : is type of value returned by specified operation.
  • op : is the operator being overloaded .
  • operator op : is funtion name and operator is keyword.

Note

  • Operator function must be either member function(nonstatic) or friend function.

How To Invoke

  1. If operator is unary then operator function can be invoked as...

    • Op X or X Op .
    • for friend function Op X would be interpreted as operator Op(X) .
  2. If operator is binary then operator function can be invoked as...

    • X Op Y.
    • for friend function X Op Y would be interpreted as X.operator Op(Y) .

Which operator can be overloaded ?

  • We can overload all C++ operator except followings......

    • class member access operators ( . , .* ) .
    • Scope resolution operator ( :: ) .
    • Conditional operator ( ?: ) .
    • Size Operator ( size of ) .

Rules For Overloading Operator

  1. Only existing operators can be overloaded. New operator can not be created.
  2. Overloaded operator follow the syntax rules of the original operators.They can not be overridden.
  3. We can not use friend functions to overload certain operators.
    Click to see those operators
    • = : Assignment operator
    • () : Function call operator
    • [] : Subscripting operator
    • -> : Class member access operator

Overloading Unary Operator

Unary Operator

operators that act upon a single operand to produce a new value are known as unary operator

Examples :

  • unary minus(-)
  • increment(++)
  • decrement(--)
  • NOT(!)
  • Addressof operator(&)
  • sizeof()

Let us consider the unary minus operator. A minus operator when used as a unary,takes just one operand. We know that this operator changes the sign of an operand when applied to a basic data item.We will see here how to overload this operator and when applied to an object should change the sign of each of its data items.

Rules :

  • Unary operator , overloaded by means of memeber function, takes no explicit arguments and return no explicit values, but those overloaded by means of friend function, take one reference argument(object of relevent class).

Code for overloading unary operator

#include <bits/stdc++.h>
using namespace std;
class Number
{
    int data;

public:
    void set(int d)
    {
        data = d;
    }
    void operator++()
    {
        data+=data;
    }
    void display()
    {
        cout << "Data : " << data << endl;
    }
    friend void operator-(Number &A);
};
// Using friend function 
void operator-(Number &A)
{
    A.data -= 2;
}
int main()
{
    Number obj;
    obj.set(5);
    obj++;
    obj.display();
    -obj;
    obj.display();
    return 0;
}
Explanation
  • In above code we have overloaded operator(++) which increment data by one but here we give special meaning to ++ and now using this we increment data by its own value.
  • In above code we have overloaded operator(-) using friend function,which decrement data by value 2.

Note :

  • the argument is passed by reference.It will not work if we pass argument by value because only a copy of the object that activated the call is passed to operator-().Therefore, the changes made inside the operator function will not reflect in the called object.

Overloading Binary Operator

Binary Operator

A binary operator is an operator that operates on two operands and manipulates them to return a result.

Examples :

  • Equal (==)
  • Not equal (!=)
  • Less than (<)< /li>
  • Greater than (>)
  • Greater than or equal to (>=)
  • Less than or equal to (<=)< /li>
  • Logical AND (&&)
  • Logical OR (||)
  • Plus (+)
  • Minus (-)
  • Multiplication (*)
  • Divide (/)
  • We have just seen how to overload an unary operator.The same mechanism can be used to overload a binary operator.Here we illustrated how to multiply two user defined object using binary operator (*).
    • Obj3 = product( obj1 , obj2 );  // Functional notation
      
      was used. The funtional notation can be replaced by a natural looking expression.
  • obj3 = obj1 * obj2 ;           // Arithmetic notation
    
    by overloading * operator using an operator*() function.

Rules :

  • Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a friend function take 2 explicit arguments.
  • When using binary operators overloaded through a member function,the left-hand operand must be an object of the relevant class.
  • Binary arithmetic operators such as +,-,* and / must return value and not attempt to change their own arguments.

    Code for overloading Binary operator

#include <bits/stdc++.h>
using namespace std;
class Product
{
    int data;

public:
    void set(int a)
    {
        data = a;
    }
    Product operator*(Product A);
    void display()
    {
        cout << "Data : " << data << endl;
    }
};
Product Product ::operator*(Product A)
{
    Product temp;
    temp.data = data * A.data;
    return temp;
}
int main()
{
    Product N1, N2, N3;
    N1.set(5);
    N2.set(10);
    N3 = N2 * N1;
    N3.display();
    return 0;
}
Explanation

In above code we have overloaded operator(*) which take an object and multiply it with left-hand object and return an object of relevant class.

Summary
  • Operator overloading is one of the important feature of C++ that enhance its exhaustibility.
  • Using Operator overloading , we can add two user defined data type such as object, with the same syntax,just as basic data types
  • We can overloade almost all the C++ operators except the followings:
    • class member access operators ( . , .* ) .
    • Scope resolution operator ( :: ) .
    • Conditional operator ( ?: ) .
    • Size Operator ( size of ) .
  • Operator overloading is done by special function operator function which can only be member function or friend function.