accessor member functions and const
From: Faheem Mitha (faheem_at_email.unc.edu)
Date: 02/02/05
- Next message: Dave Moore: "Re: mixing std::for_each with std::copy and std::ostream_iterator<T>()"
- Previous message: Mike Wahler: "Re: String handling in .txt file."
- Next in thread: Anthony Borla: "Re: accessor member functions and const"
- Reply: Anthony Borla: "Re: accessor member functions and const"
- Reply: B. v Ingen Schenau: "Re: accessor member functions and const"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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;
}
- Next message: Dave Moore: "Re: mixing std::for_each with std::copy and std::ostream_iterator<T>()"
- Previous message: Mike Wahler: "Re: String handling in .txt file."
- Next in thread: Anthony Borla: "Re: accessor member functions and const"
- Reply: Anthony Borla: "Re: accessor member functions and const"
- Reply: B. v Ingen Schenau: "Re: accessor member functions and const"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|