Apparently, a const member function is still allowed to change data that the class member are pointing to. Here\'s an example of what I mean:
class MyClass
{
In a const member function, the type of data changes from int* to int *const:
int * const data;
which means, it's the pointer which is const in the const member function, not the data itself the pointer points to. So you cannot do the following:
data = new int[100]; //error
as it's attempting to change the pointer itself which is const, hence disallowed, but the following is allowed:
data[0] = 100; //ok
Because changing the content doesn't change the pointer. data points to same memory location.
If you use std::vector, then you can achieve what you want. In fact, vector solves this problem, along with the memory management issues, therefor use it:
class MyClass
{
public:
MyClass();
int getSomething() const;
private:
std::vector data;
};
MyClass::MyClass() : data(10) {} //vector of size 10
int MyClass::getSomething() const
{
data[4] = 3; // compilation error - this is what you wanted.
return data[4];
}
Avoid non-RAII design as much as you can. RAII is superior solution to memory management issues. Here, with it, you achieve what you want. Read this: