Constant Values

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

const int i = 5;

i = 10; // Error
i++;    // Error

In C++, you can use the const keyword instead of the #define preprocessor directive to define constant values. Values defined with const are subject to type checking, and can be used in place of constant expressions. In C++, you can specify the size of an array with a const variable as follows:

const int maxarray = 255;
char store_char[maxarray];  // Legal in C++; illegal in C

In C, constant values default to external linkage, so they can appear only in source files. In C++, constant values default to internal linkage, which allows them to appear in header files.

The const keyword can also be used in pointer declarations.

char *const aptr = mybuf;  // Constant pointer

*aptr = 'a';       // Legal
aptr = yourbuf;    // Error

A pointer to a variable declared as const can be assigned only to a pointer that is also declared as const.

const char *bptr = mybuf;  // Pointer to constant data

*bptr = 'a';       // Error
bptr = yourbuf;    // Legal

You can use pointers to constant data as function parameters to prevent the function from modifying a parameter passed through a pointer.

You can call constant member functions only for a constant object. This ensures that the object is never modified.

birthday.getMonth();    // Okay
birthday.setMonth( 4 ); // Error

You can call either constant or nonconstant member functions for a nonconstant object. You can also overload a member function using the const keyword; this allows a different version of the function to be called for constant and nonconstant objects.

You cannot declare constructors or destructors with the const keyword.

See Also   Constant Member Functions