Operator Overloading

Operator Overloading

Overloading Pre-(increment & decrement) & Post-(increment & decrement)

OVERLOADING

Overloading means that users can define pre-defined stuff again according to them and make it more efficient.

Overloading Pre(increment & decrement) operator


#include <iostream>
#include <conio.h>
using namespace std;
class increAndDecre
{
    private:
    int a;//declare a integer
    public:
    //constructor
    increAndDecre()
    {
        a=0;
    }
    //parameterized constructor
    increAndDecre(int a)
    {
        this -> a = a;//a after this is member variable
    }
    increAndDecre operator ++()
    {
        //prefix increment
        increAndDecre obj;
        obj.a=++a;
        return obj;
    }
    increAndDecre operator --()
    {
        //prefix increment
        increAndDecre obj;
        obj.a=--a;
        return obj;
    }
    void display()
    {
        cout<<"\n\n a : "<<a;
    }
};
int main()
{
    increAndDecre i(10);
    increAndDecre i2=++i;
    i2.display();
    i=--i2;
    i.display();
    return 0;
}

Output of above code

Overloading Post(increment & decrement) operator

For Post-(Increment and decrement) you have to change location of operator in function


#include <iostream>
#include <conio.h>
using namespace std;
class increAndDecre
{
    increAndDecre operator ++()
    {
        //prefix increment
        increAndDecre obj;
        obj.a=a++;//change is over here
        return obj;
    }
    increAndDecre operator --()
    {
        //prefix increment
        increAndDecre obj;
        obj.a=a--;//change is overhere
        return obj;
}
}
//other wise whole code will remain same as pre-(increment & decrement)