S
subramanian100in
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 ?
Kindly explain.
Thanks
V.Subramanian
#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 ?
Kindly explain.
Thanks
V.Subramanian