Operator Overloading in C++

 

 

Like Function Overloading C++ also support the Powerful  concept of Operator overloading.Few  operators in C++ such as +,-,++,>,<,<== etc. works on Build in Data types i.e primitive data types such as  (int,char,float) that means we can directly add two integers numbers  or two float numbers .


For Example

int a,b,c;

c=a+b;


Here addition operation is performed on two operands a and b of integer data type .But what if i wants to add two user defined variables. In order to add or compare or to perform any operation on user defined data type , the concept of OPERATOR OVERLOADING is used. When two basic type operands  are added operator overloading takes place but it takes place implicitly.But in-order to perform any operation on user defined datatypes operator overloading is done Explicitly.

OPERATOR OVERLOADING

“The property to give additional meaning to Existing Operators ,so that they can work with the USER DEFINED DATA TYPES is called as operator overloading.Providing additional meaning to the existing operators ,simply extends the functionality of operator.”

Rules of Operator overloading

  1. Operator overloading can only  be done on operators which is defined in C++ .No new operators can be created such as **,&!, and so on.
  2. Intrinsic property of operators should not be changed.The properties are:
  • Precedence should be Preserved
  •  Associativity should be preserved.
  •  Arity should be preserved i.e (the number of arguments an operator takes ).

     3.Few Operators that can be overloaded.


?: (conditional)4.There are 6 operators that cannot be overloaded.

  1.  . ( member selection)
  2.  .* (member selection with pointer-to-member)
  3.  :: (scope resolution)
  4.  sizeof (object size information)
  5.  typeid (object type information)

5.Pointer Indirection Operator must return a pointer.

 3 Ways to overload operators:

 

 

There are two types of operators on which overloading is performed.

1.UNARY OPERATORS

2.BINARY OPERATORS

 

As shown in diagram there are two types of operators Unary and Binary operators.These operators can be overloaded through these methods mentioned above.

1.By creating member function of the class

2.By making a member function friend of the class.

3.By creating non member function.

SYNTAX OF UNARY AND BINARY OPERATORS IN CASE OF MEMBER FUNCTION AND FRIEND FUNCTION

Operator overloading can be performed by a special member function operator  in both the cases(member function and friend function)as shown in above syntax.

METHOD OF OPERATOR OVERLOADING

1.Create a class which consists of its own private data.

2.Declare a special member function  of Operator Op () name which represents the operator overloading method where op is the operator which will be overloaded(it can be any operator such as ++,–,*,/,>+,etc..

3.void operator op () member function can be declared and defined inside and outside the class.

4.Operator member function can be called directly as ++obj or –obj in main section of class using object.which represents object is incremented directly and thus member function operator op() will be invoked.

If declared and defined inside the class, Syntax will be :

 

If  declared inside and defined outside the class syntax is:

UNARY OPERATOR OVERLOADING USING MEMBER  FUNCTION

  • Unary operator overloading means overloading of increment (++) and decrement(–)operators.
  • A unary operator member function should be non static and should not have any argument.
  • Prefix and postfix increment and decrement operations are performed using unary operators.

Syntax of unary member function 


void operator ++()  // UNARY MEMBER FUNCTION DEFINED

{

function body….

//a++;

}


operator :  operator is the name of the special member function with which operator overloading is executed.

++: it is the increment operator  which is overloaded.

Unary overloading of  increment operator with prefix operation.

class Abc

{private:

…………

public:

void operator ++()          //declaration and definition of an overloaded member function

{

……………

……………

};

main()

{abc obj;

………..                

++obj;             //calling of an overloaded function

………..

}

In the above syntax ,increment operator is overloaded for prefix operation using member function.since we are using operator overloading to directly perform any operation on user defined data type ,Member function can be directly called by ++obj. Once ++obj is called, compiler will directly invoke the operator member function.

PROGRAM:A program of C++ to perform prefix increment on user defined datatype by overloading increment operator using operator overloading.

#include<iostream>
using namespace std;
class Abc
{private:
    int a;
    public:
        void getdata()
        {cin >>a;
        }
        void operator++()//definition of unary operator mem func. 
        {a++;
        }
        void display()
        {cout<<a<<endl;
        }
        };
int main()
{ Abc obj1;
cout<<"enter values of 1st no. "<<endl;
obj1.getdata();
++obj1;//increment operator member func.is called
obj1.display();
return 0;
}

In the above program unary operator is overloaded using member function of the class.We performed prefix increment operation on a data member a .Since we are not  returning any value return type will be void.

Unary overloading of  increment operator with prefix operation having return type.

Earlier we discussed unary overloading of an increment operator using member function without returning any value.In case

Program:A program to overload unary increment  operator using member function by returning value. 

#include<iostream>
using namespace std;
class Abc
{private:
    int a;
    public:
        void getdata()
        {cin >>a;
        }
        Abc operator++()
        {Abc temp;  //object of class Abc is created
        ++a;
        temp.a=a;   //value of a is assigned to object
        return temp; //object is returned
        }
        void display()
        {cout<<"value of a is   "<<a<<endl;
        }
        };
int main()
{ Abc obj1,obj2;
cout<<"enter values of 1st no. "<<endl;
obj1.getdata();
cout<<"enter values of 2nd no. "<<endl;
obj2.getdata();
++obj1;
++obj2;
obj1.display();
obj2.display();
return 0;
}

1.In this program unary increment  operator is overloaded using special member function of class operator op().

2.Where Member function is returning some valid value.

3.In order to return value,

Firstly an object of same class is created.

Secondly  Operation is performed as here we are incrementing value of a.++a will be done.

Thirdly: Value  of a is assigned to object data member a.i.e temp.a=a,

fourthly Value is returned in form of object.Since object is of class type,return type of class will be classname i.e Abc operator++().

Unary overloading is performed to perform direct  operation on user defined datatype.So in order to return value we need to return value as as user defined datatype. 


Abc operator++()

{Abc temp; //object of class Abc is created

++a;

temp.a=a; //value of a is assigned to object

return temp; //object is returned

}


Drawback: Infix increment operation is performed above.In order to perform postfix operation if in main part, member function  for overloading increment operator is called using  obj++  ,compiler generates an error.To execute postfix operation ,a member function should be defined as 

void operator ++(int) to differentiate between prefix and postfix operation.

Unary overloading of  increment operator with postfix operation.

Difference between prefix operation and postfix.

By defining the ++operator () function in the class we can overload  pre increment ++ operator. For overloading post increment  ++ operator we have to define operator ++ (int) operator function.

PROGRAM:A program to perform post increment operation by overloading ++ operator using member function of class.

#include<iostream>
using namespace std;
class Abc
{private:
    int a;
    public:
    Abc()
    {
    }
    Abc(int x)
        {a=x;
        }
        Abc operator+(Abc object)
        {//Abc temp;
        return(a+object.a);
        }
        void display()
        {cout<<a<<endl;
        }
            
};
int main()
{ Abc obj1(10),obj2(20),obj3;
obj3=obj1+obj2;

obj1.display();
obj2.display();
obj3.display();
return 0;
}

Program:A program to perform both prefix and postfix increment operation by overloading ++ operator using member function. 

#include<iostream>
using namespace std;
class Abc
{private:
    int a;
    public:
        void getdata()
        {a=0;
        }
        Abc operator++()
        {Abc temp;
        a++;
        temp.a=a;
        return temp;
        }
        Abc operator++(int)
        {Abc temp;
        temp.a=a;
        a++;
        return temp;
        }
        void display()
        {cout<<a<<endl;
        }            
};
int main()
{ Abc obj1,obj2;
obj1.getdata();
obj2.getdata();
obj1.display();
obj2.display();
obj2=++obj1;
obj1.display();
obj2.display();
obj2=obj1++;
obj1.display();
obj2.display();
return 0;
}

BINARY OPERATOR OVERLOADING USING MEMBER  FUNCTION.

1.Binary overloading is performed on two operators.for ex a+b.so  member function operator can be invoked directly as obj 3=obj1+obj2; here two objects can be directly added by overloading + operator.

2.Binary operator overloading includes overloading of arithmetic and comparison operators.

3.Member function definition of binary operators contains one argument in argument list.And the argument will be object of classtype.

void operator+(argument)

4.Binary Member function void operator+(argument) can be invoked as obj 3=obj1+obj2 in main part of program(where obj1,obj2 and ob3 are objects of class).

 obj 3=obj1+obj2, this invocation statement is equivalent to :-

obj3=obj1.operator+(obj2)    //called as usual function

Working procedures(features) of binary member function:

As shown in diagram :

1.It will receive only one argument of class type explicitly i.e Value of second object will be passed through an object that is mentioned in an argument.

2.Value of second object will be passed directly .

3.It Returns a value of classtype.

A program to overload binary operator + using member function of class.

#include<iostream>
using namespace std;
class Abc
{private:
    int a;
    public:
    Abc()
    {
    }
    Abc(int x)
        {a=x;
        }
        Abc operator+(Abc object)
        {//Abc temp;
        return(a+object.a);
        }
        void display()
        {cout<<a<<endl;
        }
            
};
int main()
{ Abc obj1(10),obj2(20),obj3;
obj3=obj1+obj2;

obj1.display();
obj2.display();
obj3.display();
return 0;
}

Program:A C++ program to perform arithmetic operations on user defined data types by overloading binary operators using member function of class.

#include<iostream>
#include<conio.h>
using namespace std;
class arithmetic
{
public:
 int a;
arithmetic()
{a=0;
}
arithmetic(int s)
{
a=s;
}
void operator + (arithmetic x)
{
cout<<"addition of two objects is  "<<a+x.a<<endl;
}
void operator - (arithmetic x)
{
cout<<"subtraction of two objects is  "<<a-x.a<<endl;
}
void operator * (arithmetic x)
{
cout<<"multiplication of two objects is  "<<a*x.a<<endl;
}
void operator / (arithmetic x)
{
cout<<"division of two objects is  "<<a/x.a<<endl;
}
void operator % (arithmetic x)
{
cout<<"modulus 0f two objects is"<<a%x.a<<endl;
}
};
main()
{
arithmetic x1(2),x2(6);
 x1+x2;
x1-x2;
x1*x2;
x1/x2;
x1%x2;
getch();
} 

Program:A C++ program to perform comparision operation on user defined data types by overloading binary operators using member function of class.

#include<iostream>
#include<conio.h>
using namespace std;
class comparison
{
int a;
public:
comparison()
{a=0;
}
comparison(int s)
{
a=s;
}
void operator == (comparison x)
{
if(a==x.a)
cout<<"n both are equal";
else
cout<<"n not equal";
}
void operator > (comparison x)
{
if(a>x.a)
cout<<"nfirst is bigger";
else
cout<<"nsecond is bigger";
}
void operator < (comparison x)
{
if(a<x.a)
cout<<"nfirst is smaller";
else
cout<<"nsecond is smaller";
}
void operator != (comparison x)
{
if(a!=x.a)
cout<<"nboth are not equal";
else
cout<<"nboth are equal";
}
};
main()
{
comparison x1(2),x2(6);
x1>x2;
x1<x2;
x1==x2;
x1!=x2;
getch();
}

Unary operator overloading using friend function

As discussed earlier,we can overload unary operator using friend function also.That means we can use friend function at the place of member function.

Syntax of friend function for unary operator overloading.

 

 

Steps to follow when overloading operators using friend

1.Declare member function  return type operator++(Abc &obj) as friend in the declaration part.

2.Since friend function can only be defined outside the class,definition of friend function is done outside.

3.In the argument part you will create a reference object of the same class to access the value of a datamember.

Program:A program to overload unary increment  operator
using friend  function by returning value.

#include<iostream>
using namespace std;
class Abc
{private:
    int a;
    public:
        void getdata()
        {cin >>a;
        }
    friend    Abc operator++(Abc &obj);
    
        void display()
        {cout<<a<<endl;
        }            
};
    Abc operator++(Abc &obj)
        {Abc temp;
        temp.a=obj.a++;
        return temp;
        }
int main()
{ Abc obj1,obj2;
cout<<"enter values of 1st no. "<<endl;
obj1.getdata();
cout<<"enter values of 2nd no. "<<endl;
obj2.getdata();
++obj1;
++obj2;
obj1.display();
obj2.display();
return 0;
}

Binary operator overloading using friend function.

 

 

Leave a Comment