Datasheet
If your code never catches any exceptions but an exception is thrown, it will be caught by the program
itself, which will be terminated. These trickier aspects of exceptions are covered in much more detail in
Chapter 15
The Many Uses of const
The keyword const can be used in several different ways in C++. All of its uses are related, but there are
subtle differences. One of the authors has discovered that the subtleties of
const make for excellent
interview questions! In Chapter 12, you will learn all of the ways that
const can be used. The following
sections outline the most frequent uses.
Const Constants
If you assumed that the keyword const has something to do with constants, you have correctly uncov-
ered one of its uses. In the C language, programmers often use the preprocessor #
define mechanism to
declare symbolic names for values that won’t change during the execution of the program, such as the
version number. In C++, programmers are encouraged to avoid #
define in favor of using const to
define constants. Defining a constant with
const is just like defining a variable, except that the compiler
guarantees that code cannot change the value.
const float kVersionNumber = “2.0”;
const string kProductName = “Super Hyper Net Modulator”;
Const to Protect Variables
In C++, you can cast a non-const variable to a const variable. Why would you want to do this? It
offers some degree of protection from other code changing the variable. If you are calling a function that
a coworker of yours is writing, and you want to ensure that the function doesn’t change the value of a
parameter you pass in, you can tell your coworker to have the function take a
const parameter. If the
function attempts to change the value of the parameter, it will not compile.
In the following code, a
char* is automatically cast to a const char* in the call to
mysteryFunction(). If the author of mysteryFunction() attempts to change the values within the
character array, the code will not compile. There are actually ways around this restriction, but using
them requires conscious effort. C++ only protects against accidentally changing
const variables.
// consttest.cpp
void mysteryFunction(const char* myString);
int main(int argc, char** argv)
{
char* myString = new char[2];
myString[0] = ‘a’;
myString[1] = ‘\0’;
mysteryFunction(myString);
return (0);
}
25
A Crash Course in C++
04_574841 ch01.qxd 12/15/04 3:39 PM Page 25










