fa********@gmail.com wrote:
>
Can somebody explain to me why I still can change stuff in the
private variable v??
Firstly, speaking informally, the effect of 'const' keyword used to
qualify a class method applies to _all_ data members of the class,
regardless of whether they are private or not. 'Private' has absolutely
nothing to do with the issue in question. Forget about 'private'.
Secondly, what you seem to misunderstand, is that 'const' qualifier in
C++ can be used to qualify an _access_ _path_ to certain object. When
some access path is const-qualified, it means that you can't normally
modify that object through that specific access path. At the same time
it might be perfectly possible to modify the same object using other,
alternative non-const-qualified access paths.
For example, here
int i = 5;
int* p = &i;
const int* pc = &i;
I have a variable 'i' and two access paths to that variable: '*p' and
'*pc'. The latter is const-qualified, meaning that I can't modify 'i'
through that path
*pc = 42; // ERROR
However, I can easily modify 'i' using the former access path
*p = 42; // OK
and now if I check the const-qualified access path, I'll discover that
'*pc' changed to 42.
When you declare some class method as 'const', that only means that you
can't modify the class data through the 'this' pointer. I.e. the access
path provided by '*this' is const-qualified inside the class method. If
inside your 'assign' you try to directly modify 'this->v', you'll get an
error.
void assign(typename vector<TYPE>::iterator itr, const int& n,
const Vector<TYPE>& val) const // <----- (c)
{
this->v[0] = 42; // ERROR
// or simply
v[0] = 42; // ERROR
}
This happens because of your 'const' at point (c).
However, just like I described before, if you have any alternative
non-const-qualified access paths to the inner data of your class,
there's nothing to prevent you from that data it. That's exactly what
happens in your code. An instance of your 'VectorItr' class created by
'Vector::operator()' is nothing else than an alternative
non-const-qualified access path to the inner data of that 'Vector'
object. You pass that 'VectorItr' instance into the 'Vector::assign'
method and then use it to modify the data
void assign(typename vector<TYPE>::iterator itr, const int& n,
const Vector<TYPE>& val) const // <----- (c)
{
*itr = 42; // OK
}
'const at (c) can't prevent it because it has absolutely nothing to do
with it. You provided 'assign' with a way to circumvent the "protection"
provided by 'const'. It is specifically _you_ who did it, so you really
shouldn't be surprised at all.
--
Best regards,
Andrey Tarasevich