I'm working through a textbook of examples about operator overloading and it got me wondering about returning by 'constant value' (for example with operator+
). As I understood it, if I returned anything as a const
, it was unable to be modified later. Say I have this crude example:
#include <iostream>
using namespace std;
class Temp {
private:
int val;
public:
Temp(){};
Temp(int v):val(v){};
const Temp operator+(const Temp& rhs) const {
return Temp(this->val + rhs.val);
}
int getVal() { return this->val; }
void setVal(int v) { this->val = v; }
};
int main() {
Temp t1, t2, t3;
t1 = Temp(4);
t2 = Temp(5);
t3 = t1 + t2;
cout << t3.getVal() << endl;
t3.setVal(100);
cout << t3.getVal() << endl;
}
After t3 = t1 + t2
, t3
is now a const Temp
object, not a const Temp&
; nevertheless, it is a const
. I output its val
, then modify it, though I thought I wasnt supposed to be able to do that? Or does that belong only to objects of const Temp&
?