Operator Overloading in C++ | Operator Overloading Explained With Real Life Examples

 Operator Overloading in C++



What is operator overloading?

Operator overloading means overloading an operator. 😑BRUH... I know you don't understand. Let me put it in a simple manner, suppose if I will say make a faulty calculator where "+" will do subtraction, "-" will do division, "*" will do addition, "/" will do subtraction. So you will say what are you saying Dhruv. 
Hmm, but I am not saying wrong it is possible by operator overloading.

Let's understand by your favorite example - YOUR WEDDING EXAMPLE 😍🤣( Now don't start thinking about your bride just understand this concept you boiss)

So Suppose when your bride was of 8-10 years then what she says that her father's house is her, her father's car is her car. But when her wedding happed then everything will change like the person is the same but now your bride will say Your car is her car also, your home is her home also.

So here the person is the same but ownership is changed or you can say her perception is the same.

So the same programming sign is the same but functionality will change, so you can do subtraction from the "+" operator.

Credit - edureka


Here is how you can overload an operator - 


#include <iostream>
using namespace std;

class faulty_calculator
{
    public:
    int num1;
    int res;

    //CRETING CONTRUCTOR TO INSERT VALUES
    faulty_calculator(int n1)
    {
        num1 = n1;
    }

    //OPERATOR OVERLOADING
    /*syntax - className operaotr""+/-/*or any other operator""(className obj)
    {
        className new_object
        new_object.data_member = any operation
        return new_object;
    }*/

    faulty_calculator operator+(faulty_calculator obj2)
    {
        faulty_calculator c3(122);
        c3.res =  num1 - obj2.num1;
        return c3;
    }

    /*This Above Function Is Equivalent to this below function

    int sum(faulty_calculator obj2)
    {
        return num1 + obj2.num1;
    }
    */

};
int main()
{

    faulty_calculator fc1(122), fc2(22), fc3(100);
    fc3 = fc1 + fc2;
    cout<<"SUBTRACTION BY ADDITION OPERATOR OVERLOADING IS: "<<fc3.res<<endl;

    return 0;
}


Output - 

SUBTRACTION BY ADDITION OPERATOR OVERLOADING IS: 100



Comments

Popular posts from this blog

Constructor In C++ | Constructor Explained With Real Life Example

Destructor In C++ | Destructor Explained With Real Life Examples

Array Of Objects In C++ | Array Of Objects Explained With Real Life Example