Re: Reference is not a member of class?
In article <1151312059.889096.283630@i40g2000cwc.googlegroups.com>, Oleg
<beholder@gorodok.net> writes
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
}
There is nothing wrong with that code, but there is in your
understanding of what const qualification does. It is perhaps easier to
understand with this code that uses pointers:
class test {
public :
test(int& i) :
m_i(i) {}
void f() const { * m_i = 0; } // OK do attempt to
change the pointer, only the object it is pointing to
void g(int * i_ptr) const { * m_i = i_ptr; } //
illegal
private :
int& m_i;
};
const qualification of an instance of a class type in C++ is shallow it
behaves as if you appended 'const' to each of the declared instance data
members. Of course in the case of references it is not syntactically
allowed because the semantics of references already prohibits changing
what the reference is but not the object referenced (unless you declare
it as a const reference)
--
Francis Glassborow ACCU
Author of 'You Can Do It!' and "You Can Program in C++"
see http://www.spellen.org/youcandoit
For project ideas and contributions: http://www.spellen.org/
youcandoit/projects
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]