Given the following code:
#include <iostream>
using namespace std;
class B {
private:
int n;
public:
B(int x) :
n(x) {
}
B operator+(B& b) {
return B(n + b.n);
}
friend ostream& operator<<(ostream &out, const B& b) {
out << "B: " << b.n;
return out;
}
bool operator<(const B& rhs) const {
return n < rhs.n;
}
};
int main() {
B b1(1), b2(2), b3(3);
const B b4 = b1 + (b2 + b3); // error
cout << b4 << b1 << b2 << b3;
return 0;
}
I know that if I will change this :
B operator+(B& b)
To:
B operator+(const B& b)
So it's will be ok. But, why it's really fix it?
invalid initialization of non-const reference of type 'B&' from an rvalue of type 'B'
(I understand the meaning of the error, but, I don't understand why the changing fix the error).
In addition, what is the difference between the code above (that give me error), to the following code:
class D: public B {
double m;
public:
D() :
B(0), m(0) {
}
D(int x, int y) :
B(x), m(y) {
}
D operator+(D& d) { // ~~
return d;
}
friend ostream& operator<<(ostream &out, const D& d) {
out << static_cast<const B&>(d);
out << ", D: " << d.m;
return out;
}
};
int main() {
B b4(4);
D d1(1, 0), d2(1, 2);
D d3 = d1 + d2;
cout << b4 << ", " << d3 << endl;
return 0;
}
Why now I don't get at ~~
also error?