getRadius()
returns a copy of the object’s radius, not a reference to it, so you can’t use it for modification. So the following expression:
C.getRadius()=t;
attempts to modify a temporary copy, which isn’t allowed. (The reason that its not allowed is that otherwise that code would compile but do nothing useful, giving a subtle bug rather than an easily identified compile error).
There are various options:
- return a reference,
double & getRadius();
- add a
void setRadius(double);
function, and use that for modification - make the radius public; there’s little point in using accessors unless they’re necessary to enforce invariants.
If you do want accessor functions, you should keep the existing double getRadius()
, but declare it const
. That will allow you to get, but not modify, the radius of a constant object.
solved C++ not modifiable lvalue