Sessions on advanced C++ programming
Half-day seminar at CCC
Author: Zoltán Porkoláb
Budapest, 2007
A.1. Constant magic
Topics
- Arrays and string literals
Be carefull the difference between character arrays and
string literals. Arrays are alwais allocated in the user
data area, and they are mutable, string literals, however, has type
const char array, and they are frequently allocated in read-only
areas. Modification attempt of such literals can cause run-time
errors.
- When constant is stored in memory
The fact, that a C++ object is constant, doesn't mean memory is not
allocated to store it. There is a different concept here: whether
the value of the constant is known at compilation
time. Value known in compilation time is called constant
expression.
- Using constants to detect errors
Constants could be used to map semantic information to the
language syntax. Therefore the compiler at least has some
chance to detect the problem.
- Scope rules for constants
Constants have static linkage by default - similarly to
typedef. This could allow confusion between source files.
However, it is possible to declare a const as extern, so
one can define the value of a constant in exactly one source file,
and declare it in the other files.
- Constant class members
Class members could be - and frequently should be - constants.
Constant class attributes (data members) should be
initialized in the initializer list of a constructor.
Initializer list also used to initialize subobjects without
default constructors and reference members.
- Static const
One can define a static const member in a class, and
can use similar way to the non-const static members: this members
must be defined outside of the class definition: tipically
in the .cpp file. However, there is an exceptional rule for
integral data types: those could be initialized inside
the class definition.
- Constant memberfunctions
Class methods (member functions) could be defined as constant.
This qualifier means two things: first this functions are allowed
to be called on constant objects, second: there is a compilation
time guarantee, that such methods do not alter their objects.
The this pointer for constant members are declared as
pointer to const
- Const_iterator
Iterators to constant: const_iterator is used in the STL
library. It has similar role to the pointer to constants for
ordinary types. Operator* and Operator-> for const_iterator return
with const reference, so they are not left values. Be care:
const_iterator and const iterator is not the same!