su**************@yahoo.com wrote:
Consider the following program:
#include <iostream>
using namespace std;
class Base
{
public:
Base(int x = 0);
int val;
};
Base::Base(int x) : val(x)
{
}
class Test
{
public:
Test(Base & arg, Base * p);
Base & obj;
Base another;
Base * ptr;
};
Test::Test(Base & arg, Base * p) : obj(arg), another(arg), ptr(p)
{
}
int main()
{
Base a(9);
Base b(100);
const Test t(a, &b);
t.obj.val = 0;
t.another.val = 100;
t.ptr->val = 2000;
return 0;
}
When I compile this program under g++, I get
// x.cpp:36: error: assignment of data-member `Base::val' in read-only
structure
When I compile this program under VC++ 2005 Express Edition, I get
// x.cpp(36) : error: 't' : you cannot assign to a variable that is
const
When I have const Test t, the data member "Base another;"
becomes constant and hence the compilation error for modifying
t.another.val
But why the other two data members
Base & obj;
Base * ptr;
are not treated as const ? Why don't I get compilation error for
modifying
t.obj.val and t.ptr->val ?
A member of a const object is const. I.e. you cannot change the value
of that object. If your 'Test' contains a member, and an instance of
'Test' is declared 'const', no members of that instance will be allowed
to change. However...
If I declare
struct A {
int *pointer;
};
what is the *nature* of the member? What's its *type*? What does
an instance of 'A' contain? Is that an 'int'? What cannot I change
when 'a' is declared as such
int i = 42;
A const a = { &i };
? Can I change 'i'? Can I change a.pointer? Can I change 'i' using
'a.pointer'? If any of the answers are 'yes', then can you show how?
Now, let's imagine that 'pointer' is not just a pointer to 'int', but
a pointer to another struct:
struct Int {
int value;
};
struct A {
Int *pointer;
};
Int i = { 42 };
A const a = { &i };
Looks about the same, right? Now, the same questions: can I change
'i'? Can I change 'a'? Can I change 'a.pointer'? Can I change the
object to which 'a.pointer' points? BTW, to what object does the
member 'a.pointer' points?
Can you do this as if it is your homework? Try to find the answers
yourself and then post them to see if you got them right.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask