If i have the following:
class Array{
public:
Array (int n=2) : _n(n), buf(new int[n]) {}
int & operator[](int i) const
{
return _buf[i];
}
int _n;
int* _buf;
};
int main()
{
Array arr1;
const Array arr2;
arr1[0]=1;
arr1[1]=2;
arr2[0]=arr1[0];
++arr2[0];
std:: << arr2[0]<<std::endl;
}
the program will compile and will print ‘2’, but im a bit confused.
what does the const declaration in arr2 protects exactly?
obviously not the content of the object?
please help me to understand.
thank you!
The C++ compiler only enforces that
constwill protect the members of this object, not other objects referenced indirectly (e.g. via pointer)._bufis a pointer member and what it points to is not protected by the compiler.However, many classes override based on
constin order to also protect access to associated objects. To do that, you’d write:This propagates
conston the object toconston the subscripted element.