On 2007-10-26 10:21,
in*************@gmail.com wrote:
Hi
The following code compiles fine on VC++2003, but am I violating any
standards in writing such code? More specifically, why can a const
member function call a non-const member function of a reference type
member? It seems strange and unintuitive to me. Thanks!
class T
{
public:
void B() { a = 10; }
private:
int a;
};
class A
{
public:
A(T& t_): t(t_) {}
void Test() const
{
t.B();
}
private:
T& t;
};
int main()
{
T t;
A a(t);
a.Test();
}
When a is const it means that a is const, not that any other objects
that a might know about are const too. Since t is a reference to a non-
const T there is nothing wrong with calling functions that modify t.
What happens when a is const it that you can not modify any of its
members, which means that you can not make a refer to some other object
(though that is not possible when a is non-const either, but if you make
t a pointer instead there would be a difference).
--
Erik Wikström