In the below example we see that a function declared as const member of a class allows us to modify the contents of data member of the class. A brief explanation about the const member functions and const pointers are given in order to understand the behavior of the const Member Functions().
So the lesson to learn here is that the const keyword on member functions does not ensure that your object will not change at all.
class String
{
private:
char* rep;
public:
String (const char*);
void toUpper() const;
};
String :: String (const char* s)
{
rep = new char [strlen(s)+1];
strcpy (rep, s);
}
void String :: toUpper () const
{
for (int i = 0; rep [i]; i++)
rep[i] = toupper(rep[i]);
}
int main ()
{
const String lower ("lower");
lower.toUpper();
cout << lower << endl;
return 0;
}
A const member function, is a member function that does not mutate its member variables.
const on a member function does not imply const char *. Which would mean that you can't change the data in the address the pointer holds.
Your example does not mutate the member variables themselves.
A const on a member function, will ensure that you treat all of your member variables as const.
That means if you have:
int x;
char c;
char *p;
Then you will have:
const int x;
const char c;
char * const p; //<-- means you cannot change what p points to, but you can change the data p points to
There are 2 types of const pointers. A const member function uses the one I've listed above.
It only ensures that each member variable will be treated as const. And for pointers, there is a big diff between const char * and char * const.
In the following statement, pOne is a pointer to
a constant integer. The value being pointed to can’t be changed:
const int * pOne; // pointer to a
constant integer
In this next statement, pTwo is a constant
pointer to an integer. The integer can be changed, but pTwo can’t point to
anything else:
int * const pTwo; // constant pointer to
an integer
In this third statement, pThree is a constant
pointer to a constant integer. The value being pointed to can’t be changed, and
pThree can’t be
changed to point to anything else:
const int * const pThree; // constant
pointer to a constant integer
The trick to keeping this
straight is to look to the right of the keyword const to find out what
is being declared constant. If the type is to the right of the keyword,
the value is constant:
const int * p1; // the int pointed to is
constant
If the variable is to the
right of the keyword const,
the pointer variable itself is constant:
int * const
p2; // p2 is constant, it can’t point to anything else
Most of the time a const member function will mean that the member function will not modify the object itself, but this is not always the case, as the above example shows.
No comments:
Post a Comment