Operator Overloading in C++ || OOPs Concept || C++

Operator Overloading in C++ : -

The mechanism of giving some special meaning to an operator is called as Operator Overloading. 
When an operator is overloaded, it's original meaning is not lost. For example, the operator "+" has been overloaded to add two vectors, but it can still be used to add two integers. 
Hence, when operator is overloaded then basically that operator performs some additional / special operation without losing it's original operation. 
Also, when any operator is overloaded it behaves as a data-type. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using '+'

Some Instructions for Operator Overloading : 
  1. Two operators ' = ' and ' & ' are already overloaded by default in C++.
  2. Both Unary and Binary operators can be overloaded in C++.
  3. When Unary operator is overloaded as a function then it does not return any value and does not takes an argument also. 
  4. When Unary operator is overloaded as a friend function then it does not return any value but takes one argument as a parameter.
  5. When Binary operator is overloaded as a function then it returns a value and can take upto one argument as a parameter.
  6. When Binary operator is overloaded as a friend function then it returns a value and can take upto two argument as a parameter.
There are some operator which cannot be overloaded in C++ :-
  • " sizeof " -  size of operator
  • " . "           -  member selection operator
  • " :: "          -  scope resolution operator
  • " ? : "        - ternary operators 

Syntax of Operator Overloading : - 


class className {
    public
       returnType operator symbol (arguments) {
           
       } 
};

Example of Operator Overloading : -


#include <iostream>
using namespace std;

class Increm
{
    int num;

    public:
    setval(int n)
    {
        num = n;
    }
    Increm operator++()
    {
        num = num + 2;
    }
    void print()
    {
        cout << "The Incremented Value is : " << num;
    }
};

int main()
{
    int n;
    cout << "Enter a number: ";
    cin >> n;
    Increm i;
    i.setval(n);
    ++i;
    i.print();
    return 0;
}

OUTPUT:-



//ENJOY CODING\\

Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post