-2

We have a class (assuming there are some operations in functions, but constructor is default):

class X
{
public:
    X& operator=(const X& rhs){}
    const X& operator+(const X& rhs) const {}
    const X& operator+(int m) {}
}; 
X a, b, c;

Q1: Why is a = a + 5 + c; allowed and a = b + c + 5; is not? We have:

Error C2679 binary '+': no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion).

Q2: Why (c = a + a) = b + c; begins with b+c operation and not with a+a? (I found that out while debugging).

P.S. It's theoretical question only.

Archont
  • 101
  • 1
  • 9
  • `(c = a + a) = b + c;` is undefined behavior as you are reading and writing to to the same variable in a single sequence point. – NathanOliver Jan 31 '17 at 14:05
  • 1
    offtopic: why your `operator+` returns `&` ? I found a great example of operators overloading in this [answer](http://stackoverflow.com/questions/4421706/operator-overloading/4421719#4421719) – Yuriy Ivaskevych Jan 31 '17 at 14:05
  • @NathanOliver, in Visual Studio it at least executes fine. The question was, why such order? – Archont Feb 01 '17 at 07:50
  • @YuriyIvaskevych, i found that example while doing some C++ tests, so i can't really answer the question) – Archont Feb 01 '17 at 07:51
  • I see no logic in making the addition operator affects the original object. It should add add some member data of the tow objects and return the result at return. So `x = a + b` who will be affected is `x` not a nor `b`. `int a = 5, b = 7, c = 0; c = a + b;` so `c` is `12` and `a` and `b` are not affected. This is what you should take in count. – Raindrop7 Feb 01 '17 at 12:15

1 Answers1

1

Why is a = a + 5 + c; allowed and a = b + c + 5; is not?

const X& operator+(int m) {} is not a const function, and the return from the + operators is const X. Make this a const function and it'll work fine; (apart from returning a reference after this operation is very strange)

UKMonkey
  • 6,941
  • 3
  • 21
  • 30
  • I tried it and it really works! I still don't get it... How making function a const influence operator calling? – Archont Feb 01 '17 at 11:54
  • 1
    `const X& operator+(int m) {}` this function says that it will change the X that it's going to be operating on - meaning it can't be done on a const object. `const X& operator+(const X& rhs) const {}` this function says that it will return a const X& – UKMonkey Feb 01 '17 at 12:06