Re: assignment operator and const members
On 21 Nov., 20:58, Jonathan Jones <clcppm-pos...@this.is.invalid>
wrote:
I guess the problem that lead to my original question (wanting
assignment to work with const members), is that C++ doesn't fully
support it. What I _really_ want is this:
struct Object
{
Object(int data, ...) : data_(data), ... {}
Object(const Object& r) : data_(r.data_), ... {}
foo() { ... } // can modify everything except data_
bar() { ... } // can modify everything except data_
baz() { ... } // can modify everything except data_
Object& operator=(const Object& r) { data_=r.data; ... }
private:
const int data_;
// lots of non-const data
};
I wonder why you want data_ to be const when you want to change it
some places (at least in the assignment operator). After all, you
should have control of the class and if you don't want foo or bar to
change data_, then simply don't change data_ there.
I can understand that you can have functions where you often don't
want to change data, except for special functions, but I do not find
it reasonable that you expect the type system help you with such a
specific case - it like if you had an integer, that you only want to
have bitwise manipulations on: you must program yourself out of it.
If you really care about such a special situation (I would not), you
must use another solution - e.g. by declaring data_ const and do a
const_cast that one place where you want to allow it. I would not
hesitate to turn that stuff down in a code review, however.
/Peter
/Peter
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]