Ad

C++ Operator Overloading

Operator overloading means use of existing operators and perform a new task according to user-defined action.

We can overload all the CPP operators except the following:

  1. Scope resolution operators (::)
  2. Dot operator (.)
  3. Sizeof operator
  4. Conditional Operator or Ternary Operator (? :)
  5. New operator

Rules for Overloading Operators:

  1. Only Existing Operator can be overloaded.
  2. The overloaded operator must have at least one operand.

Operator overloading is defined like a function but with a operator keyword followed by a operator which you want to overload.

Types of Operator Overloading:

  1. Unary Operator Overloading
  2. Binary Operator Overloading

Unary operator

Unary operator works on just one operand. It takes no argument in the function definition. Unary operators are minus(-), increment(++), decrement(--)

Example 1: Input number and reverse the sign (if positive convert into negative, if negative convert into positive) using unary operator overload.

#include<iostream.h>
#include<conio.h>

class unary
{
    int a;
public:
    void input();
    void output();
    operator -() // unary operator defination
    {
        a=-a;
    }
};

void unary::input()
{
    cout<<"Enter Number: ";
    cin>>a;
}
void unary::output()
{
    cout<<"Value = "<<a;
}

int main()
{
    unary obj1;
    obj1.input();
    -obj1; //operator minus(-) call
    obj1.output();
    return 0;
}
Run 1:
Enter number: 25
Value = -25

Run 2:
Enter number: -15
Value = 15

Binary operator

Binary Operator works on two operands. It takes only one argument in the function definition.

//calling syntax: 
c3=c1+c2
    or
c3=c1.operator+(c2)

Example 2: Input 2 numbers and find sum using binary operator overload.

class binary
{
    int a;
public:
    void input();
    void output();
    binary operator+(binary obj2){
        binary obj3;
        obj3.a = a + obj2.a;
        return obj3;
    }
};

void binary::input()
{
    cout<<"Enter number: ";
    cin>>a;
}
void binary::output()
{
    cout<<"Result = "<<a;
}

int main()
{
    binary obj1, obj2, obj3;
    clrscr();
    obj1.input();
    obj2.input();
    obj3 = obj1 + obj2; // operator overloading call
    obj3.output();
    getch();
}
Enter number: 10
Enter number: 20
Result = 30

Binary Operator Overloading using Friend keyword

Operator overloading can be use using friend keyword. The only difference is that a friend opertor overloading requires two arguments in the operator definition.

//calling syntax: 
c3=c1+c2 
    or
c3=operator+(c1,c2)

C Language Feedback, Questions, Suggestions, Discussion.