C++ const member function question

I

indrawati.yahya

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();
}
 
G

Guest

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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top