Rasmi Ranjan Nayak
Rasmi Ranjan Nayak

Reputation: 11998

How operator oveloading works

I have below code

class rectangle
{
    //Some code ...
    int operator+ (rectangle r1)
    {
        return(r1.length + length);//Length is the 1st argument of r1, r2, r3
    }
};

In main function

int main()
{
    rectangle r1(10,20);
    rectangle r2(40,60);
    rectangle r3(30,60);
    int len = r1 + r3;
}

Here if we will see in operator+(), we are doing r1.length + length. How the compiler comes to know that the 2nd length in return statement belong to object r3 not to r1 or r2? I think answer may be in main() we have written

int len = r1 + r3;

If that is the case then why do we need to write in

operator+ (....) 
{
    r1.lenth + lenth; //Why not length + length?
}

Why not length + length? Because compiler already knows from main() that the first length belong to object r1 and 2nd to object r3.

Upvotes: 0

Views: 244

Answers (6)

akton
akton

Reputation: 14386

The compiler needs to differentiate the length member variable of the rectangle, this->length, from r1.length. Writing length + length would mean the variable in local scope, this->length, would be used for both sides of the addition.

Upvotes: 1

PaperBirdMaster
PaperBirdMaster

Reputation: 13298

The operators are like a member function of the class rectangle but with another call format.

You can also call as a function int len = r1.operator+(r3); as suggested by other users.

So, when you write an operation using an operator from your class, the compiler tries to match the call with some of the given operators; in your call:

int len = r1+r3;

The compiler looks for an operator+ that returns something that could be put into an int and receives a rectangle as a parameter and it found your int operator+(rectangle r1) function; then calls this function with the r3 parameter and returns the int result.

The parameter given to the int operator+(rectangle r1) function is a copy of r3 so, it is why is operating over r3 and not over r1 or r2.

This is no mentioned in the question, but I think is worthy to mention:

It seems that your operator+ doesn't suits the model that operators follows usually, if you're going to add a rectangle and getting an object different from rectangle from the operation it doesn't looks like an operator; I think you must think about what you want to get and what a summatory of rectangles is.

As a binary operator it usually gets and returns the same kind of object (in order to use it in operations chain) and must be const because it doesn't changes the object itself:

class rectangle
{
    // Reference in order to avoid copy and const because we aren't going to modify it.
    // Returns a rectangle, so it can be used on operations chain.
    rectangle operator+(const rectangle &r) const
    {
        rectangle Result;
        // Do wathever you think that must be the addition of two rectangles and...
        return Result;
    }
};

int main()
{
    rectangle r1(10,20);
    rectangle r2(40,60);
    rectangle r3 = r1 + r2;
    // Operation chain
    rectangle r4 = r1 + r2 + r3;
    rectangle r5 = r1 + r2 + r3 + r4;

    // Is this what you're looking for?
    int width = (r1 + r3).width();
    int height = (r1 + r3).height();
}

If it is an unary operator the parameter and return value must be of the same type too, but the return value must be the object that takes part of the operation:

class rectangle
{
    // Reference in order to avoid copy and const because we aren't going to modify it.
    // Returns a rectangle, so it can be used on operations chain.
    rectangle &operator+=(const rectangle &r) const
    {
        // Do wathever you think that must be the addition of two rectangles and...
        return *this;
    }
};

int main()
{
    rectangle r1(10,20);
    rectangle r2(40,60);
    rectangle r3 = r1 + r2;
    // Weird operation chain, but it's only an example.
    rectangle r4 = (r1 += r2) += r3;
    rectangle r5 = (r1 += r2) += (r3 += r4);
}

Upvotes: 1

Emilio Garavaglia
Emilio Garavaglia

Reputation: 20759

Operator overloading works no more/no less than regular function call.

Think to a+b as a.operator+(b).

Apart the strange name there is no difference in that call than in a.add(b).

if the function add signature is int A::add(A x) (whre A is a class), b is copied into x, and -inside add body- x and all the members of a are accessible.

But this has nothing special with operators. It relates to parameter passing (C++ defaults to "by copy") variable scope and visibility.

If you can understand that, operator overloading should be come obvious. If you cannot, step back to "function, member functions and parameters", and don't move away from there until those concept are not clear.

Upvotes: 0

Coding Mash
Coding Mash

Reputation: 3346

Each variable inside an object is distinct from the variables of another object. The compiler will know only if you pass the object via parameter to it. It has no other means of knowing that. When you call the function, a copy of your object is created on the stack. The name you have specified in the parameter list would be the one compiler will use, regardless of the name you have used when you called the function.

int operator+(rectangle r1)
    {
        return(r1.length+length);
    }

r1 + r3; //In main

In this example, the name of your object in the function call is r1. You can name it anything. Compiler does not know that its name was r3 when it was called in main. And you are returning an integer from the function. Better create a temporary object and return it by value.

Upvotes: 2

Vikdor
Vikdor

Reputation: 24134

int len = r1+r3;

This gets resolved to

int len = r1.operator+(r3);

So, the method is called on r1 object and any references to members in operator+ will be to the members of r1 and r3 is the actual argument to that method.

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258678

You're confusing variable names with argument names. In the operator overload, you named your parameter r1:

int operator+(rectangle r1)
{
   return(r1.length+length);
}

that means that whatever parameter you pass to operator +, inside the body of the operator it will be named r1 (regardless of its original name).

r1.length is the length of the parameter, and length is the length of the current object (i.e. this->length).

//Why not length + length?

This would just return the double of the current object's length.

Let's analyse the code:

rectangle r1(10,20);
rectangle r2(40,60);
rectangle r3(30,60);
int len = r1+r3;

The last call is equivalent to r1.operator+(r3). Inside the operator, length represents r1.length and r1.length represents r3.length. Actually, not even r3.length, since you're passing by value, and a copy will be created. The usual syntax would be:

int operator+(const rectangle& r1)
{
   return(r1.length+length);
}

Also, adding rectangles doesn't really make sense, at least how you defined it. It's not intuitive that adding two rectangles returns the sum of the lengths. It should at least return a different shape.

Upvotes: 5

Related Questions