Re: Reference is not a member of class?
Oleg wrote:
This code compiles on Test Drive Comeau C++ Online and on VC
7.1. So, I assume that it is standard compliant. but why it is
allowed to modify non-const reference in const method?
class test
{
public :
test(int& i) :
m_i(i) {}
void f() const
{
m_i = 0;
}
private :
int& m_i;
};
int main()
{
int i = 1;
const test t(i);
t.f(); // set i to 0
}
Because it doesn't modify the reference. It modifies what is
referred to. From the compiler's point of view, const is
bitwise; it affects the direct members of the class, and only
the direct members. In this case, the direct member is a
reference, which cannot be modified, const or not.
Experience has shown that from a design standpoint, logical
const is preferrable to bitwise const. But the compiler is
dumb; it doesn't know the actual abstractions you are
implementing, nor the logic behind the code. So we have mutable
and const_cast, for the occasional case where a bitwise
modification doesn't modify the logical value of an object, and
we depend on programmer discipline to ensure that const is
propagated correctly to the elements not covered by bitwise
const.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]