Furthermore, how would the function even know about the month variable to modify it without it being passed in?
Member functions (like setMonth()
) implicitly receive a this
pointer to the object of type (in this case) Date
they are invoked on. For member functions qualified as const
, the this
pointer is a pointer to const
, which won't allow you to modify the state of the pointed object.
In fact, the following:
void Date::setMonth( int mn )
{
month = mn; // Modifies data member
}
Is equivalent to the following:
void Date::setMonth( int mn )
{
this->month = mn; // Modifies data member
// ^^^^^^
// "this" is a pointer to an object of type Date (i.e. Date*),
// and that is the object on which setMonth() is invoked
}
Same story for all other member functions, so:
int Date::getMonth() const
{
return month; // Doesn't modify anything
}
Is equivalent to:
int Date::getMonth() const
// ^^^^^ Means the implicit "this" pointer is const
{
return this->month; // Doesn't modify anything
// ^^^^^^
// Here, "this" is a pointer to a CONST Date object (i.e. Date const*),
// and that is the object on which getMonth() is invoked
}
IMPORTANT: The implicit this
pointer is actually a pointer to const
if the object on which the member function is invoked has a const
-qualified type.
This is why you cannot invoke a member function which is not itself const
-qualified on an object whose type is const
-qualified: the state of a const
object should never be altered, and a non-const
function does not promise to never alter it.
Therefore, the compiler will prevent you from calling a non-const
function (e.g. Date::setMonth()
) on an object of a const
-qualified type (e.g. const Date
) by raising an error.