Game Development Reference
In-Depth Information
Constant Pointers
Pointers can also be made to be constant; however, the logic is a little more involved. Listing 9-14
shows the different types of pointer constant that we can create.
Listing 9-14. Three Types of Constant Pointer
const char* const NAME = "Bruce Sutherland";
const char* BOOK = "Learn C++ Game Development";
char* const YEAR = "2014";
The first example shows the type const char* const . When dealing with constant pointers we read
the type keywords from right to left so this first example gives us a constant pointer to a character
constant. In practice this means that you cannot change the address to which the pointer points or
the data that it points at.
The second example is a pointer to a character constant. You cannot change the text data but you
can change the address pointed to, so adding the following line would be valid.
BOOK = NAME;
This would result in both BOOK and NAME pointing to the string "Bruce Sutherland" .
The remaining example is a constant pointer to character data. You can't change the pointer but you
can change the data pointer to it, so you can do the following.
YEAR[0] = '3';
The array operator would not have compiled if it was used on either NAME or BOOK , as the character
data was constant.
Constant Parameters
It is a straightforward task to make parameters constant. Listing 9-15 shows a function with constant
parameters.
Listing 9-15. Constant Parameters
bool ConstParams(const int numLetters, const char* const stringData)
{
return strlen(stringData) == numLetters;
}
This example uses a C-style string just for the purposes of the example. As you can see, we can
pass constant built-in types or constant pointers to functions or class member methods.
Constant Member Methods
This last section on constants will show you how to create constant member methods. Listing 9-16
shows an example.
 
Search WWH ::




Custom Search