According to the C++ Standard (9.2.3.2 Static data members)
1 A static data member is not part of the subobjects of a class...
And (9.2.2.1 The this pointer)
1 In the body of a non-static (9.2.1) member function, the keyword
this is a prvalue expression whose value is the address of the object
for which the function is called. The type of this in a member
function of a class X is X*. If the member function is declared
const, the type of this is const X*,...
And at last (9.2.2 Non-static member functions)
3 ... if name lookup (3.4) resolves the name in the id-expression to a
non-static non-type member of some class C, and if either the
id-expression is potentially evaluated or C is X or a base class of X,
the id-expression is transformed into a class member access expression
(5.2.5) using (*this) (9.2.2.1) as the postfix-expression to the
left of the . operator.
Thus in this class definition
class A
{
public:
static int a;
void set() const
{
a = 10;
}
};
the static data member a
is not a subobject of an object of the class type and the pointer this
is not used to access the static data member. So any member function, non-static constant or non-constant, or a static member function can change the data member because it is not a constant.
In this class definition
class A
{
public:
int a;
void set() const
{
a = 10;
}
};
the non-static data member a
is an subobject of an object of the class type. To access it in a member function there is used either a member access syntax of this syntax is implied. You may not use a constant pointer this
to modify the data member. And the pointer this is indeed has type const A *
within the function set
because the function is declared with the qualifier const
. If the function had no the qualifier in this case the data member could be changed.
const
means a member function of an object cannot modify that one object. It can modify other objects of the same class, orstatic
data, which is associated with the class, not any particular instance of it. (Ormutable
data members, which were created to be the exception to this rule.)