# store the value of a const in a non const?

## Recommended Posts

Piranjah    120
Ok, I'm starting to feel stupid:-s I want to store the variable of a const double in a non const double. So: SCP.GetPostion().X() //returns a const double and I,m doing the following: double m_PreviousSCPX = SCP.GetPostion().X(); But when compiling it give me this error: "error C2166: l-value specifies const object" Just for the record, I'm not planning changing the "getposition"-function as this was existent code:s. Anyone can help me with this extreme newbie problem?:-(

##### Share on other sites
Trillian    410
The problem is not storing the value in a non-const variable. The problem is that either GetPosition() doesn't have a constant version returning a constant reference or that X() doesn't have such version. You should have those defined :

Vector & GetPosition();
const Vector & GetPosition() const;
// or
Vector GetPosition() const;

double X() const;
// and maybe
double & X();

EDIT : If you really can't modify that code, then I think you'll need to use const_cast

##### Share on other sites
the_edd    2109
Actually, it looks like your trying to modify a member variable in a member function declared const.

You'll notice that you get the same error with this snippet, which is roughly analogous to what you're doing, I imagine:

struct X{    int get() const { return 1; }	    // error: function declared const, can't change m_    void do_it() const { m_ = get(); } 	    int m_;};int main(){    X x;    x.do_it();    return 0;}

do_it()'s const qualification guarantees that it won't change the state of the object. But of course, you are.

One solution, is to declare the corresponding member as mutable. This is an acceptable solution if:

1. objects of your class appear not to change from the outside i.e. it's "logically const", even it isn't actually constant.

2. your class isn't accessed simultaneously by multiple threads that assume const-ness means they can all "read from an object" without synchronisation (threading can break logical const-ness).

Another workaround is to declare m_ a pointer and modify what m_ points at. But this involves more overhead and is merely simulating a mutable qualification.

The last solution, is to remove const qualification from your do_it() equivalent, because it really isn't const.

But IMHO, mutable was invented for this kind of thing.

Edd

Piranjah    120