Question

Let X be a class with member function f().

this is an implicit argument for f(), it is of type X* const.

Then, if f() const is a const member function, the type for the this pointer is now const X* const.

In both cases, it seems that the type for the this pointer is const. Why then is it allowed inside the function f() definition to modify any data member of class X? Shouldn't we always resort to const_cast as in

void X::f() {        
       const_cast <int&> (member) = 1;    
} 

If f() const is const, then this is the way to do:

void X::f() const{        
       const_cast <int&> (member) = 1;    
}

(or you can also have member mutable)

But why is this working

void X::f() {  
       member = 1;    
}
Was it helpful?

Solution 2

This pointer is a rvalue. It cannot be assigned a value, so that this pointer is a const pointer does not matter.

If f() is a non const member function, this pointer points to non const X, so data member of X can be modified.

But if f() const is a const member function, this pointer points to const const X, so data member of X cannot be modified. Then, it need for data member to be mutable or to const_cast if one wants to modify it inside f() const definition.

We can do, for const_cast,

void X::f() const{        
       const_cast <int&> (member) = 1;    
} 

If member is a reference to a non-const int, then assignment is accepted by compiler and have wanted behavior. If member is reference to a const int, behavior is not predictable. Compare these:

const int a = 10;
const int* b = &a;
int* c = const_cast<int*>(b);
// *c = 20; 

c is a const_cast of a const int* whose pointee a is const. Behavior is undefined.

int a1 = 10;
const int* b1 = &a1;
int* c1 = const_cast<int*>(b1);
*c1 = 20;  

c1 is a const_cast of a const int* whose pointee a is const. This is working, you can freely assign new value to int pointed by c1.

It is known that const member function cannot change value of data members. What we say her is that this is because then, this pointer's pointee is const.

OTHER TIPS

this is implicit argument for f(), it is of type X* const.

Not quite (it's actually an rvalue of type X*), but close enough for the sake of this question.

In both cases, it seems that type for this pointer is const. Why then is it allowed inside the function f() definition to modify any data member of class X ?

Because if the pointer is const (as in X* const), you can't change the pointer. You can change whatever it points to. If it's a pointer-to-const (as in const X*), then you can't change what it points to.

So you can never modify this itself; you can't write this = &some_other_object. In a const member function, you also can't modify the (non-mutable) members of *this without a dodgy const_cast.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top