Priority

Hi
In this code , compiler first calculate ob1=ob2 or ob2=ob3 ( in that line that has written ob1=ob2=ob3 ) ?


#include <iostream>
#include <conio.h>
using namespace std;

class loc
{
private:
int longitude;
int latitude;
public:
loc() {} //needed to construct temporaries
loc(int lg, int lt)
{
longitude = lg;
latitude = lt;
}

void show()
{
cout << longitude << "\t";
cout << latitude << endl;
}

loc operator=(loc op2);

};



//******************
loc loc::operator=(loc op2)
{
longitude = op2.longitude;
latitude = op2.latitude ;
return *this; // return object that generated call
}
//**********************


int main()
{

loc ob1(10, 20), ob2(5, 30), ob3(90, 90);

ob1 = ob2 = ob3; //multiple assignment
cout << "ob1=";
ob1.show(); //display 90, 90
cout << "ob2=";
ob2.show(); //display 90, 90
cout << "ob3=";
ob3.show(); //display 90, 90
getch();
return 0;
}
As you should be able to see, operator= is evaluated from right to left.
That's a good thing too, otherwise
ob1 = ob2 = ob3; would have the same effect as ob1 = ob2;

When in question, check this:
http://www.cppreference.com/wiki/operator_precedence

It's not a good idea to return a copy in operator=, by the way. For such a small object it doesn't matter, but generally, you should return a const reference.
Last edited on
loc loc::operator=(loc op2) should be
loc& loc::operator=(const loc &op2)

You'll probably find that the compiler's using it's own generated one rather than yours.
Topic archived. No new replies allowed.