accessor member functions and const

From: Faheem Mitha (faheem_at_email.unc.edu)
Date: 02/02/05


Date: Wed, 02 Feb 2005 06:22:46 GMT

Dear People,

Please consider the following code. The functions val and wval are,
respectively, read-only and write access member functions of the class
model.

I have two simple questions.

1) Does my implementation look reasonable? In the both the read-only
and write access case, I want to be able to reference the returned
value v.

2) Using

int& wval() const {return v;}

gives

invalid initialization of reference of type 'int&' from
   expression of type 'const int'

I'm not sure why this is a problem. My understanding is that

a) The const int& guarantees that the function returns a constant
reference, so one cannot modify the object via the reference.

b) The const after the wval() means that the function is declared
const, so it is not allowed to modify the class object.

However, even if the function itself is not allowed to modify the
class object, I don't see why one cannot modify it via the non-const
reference that the function returns.

Thanks in advance for any replies.

                                                           Faheem.

**********************************************************************
class model
{
private:
  int v;
public:
  model(const int& _v):v(_v){}
  model(){}
  const int& val() const {return v;}
  int& wval() {return v;}
};

int main()
{
  model mod(0);
  mod.val() = 1; // compile error; attempt to assign to read-only location.
  mod.wval() = 1; // Ok.
  return 0;
}



Relevant Pages

  • Re: accessor member functions and const
    ... > reference the returned value v. ... int& val ... const int& valconst ... so one cannot modify the object via the reference. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: accessor member functions and const
    ... I want to be able to reference the returned ... const int& getValconst ... so one cannot modify the object via the reference. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Using const qualifier
    ... But it returns a pointer through which you could modify the list. ... Do you use "const" to imply "I will not change this, ... const int *operate; ... constraint: typeofis typeof; ...
    (comp.lang.c)
  • Re: help: class compile error
    ... > defines a global int i. so I can use ... > class CTest ... reference, unless they somehow _change_ the arguments. ... take its argument by a _const_ reference (unless it intends to change ...
    (comp.lang.cpp)
  • Re: Passing primitive variables by reference in JavaScript
    ... referred to by the same property, as your wrapper object has a property to ... to find it in order to modify and read its value. ... sense except as a marker because its value is a reference to the calling ... int main ...
    (comp.lang.javascript)