C++: OOP: const
member functions
const
member functions can use const
objects
Member functions should be declared with the const
keyword after them if they can operate on a const (this) object.
If the function is not declared const
, in can not
be applied to a const object, and the compiler will give an
error message. A const
function can be applied
to a non-const
object
A function can only be declared const
if
it doesn't modify any of its fields.
More efficient code
I remember something about compilers being able to generate more
efficient code for const
member functions.
Syntax
The const
keyword is placed after the function header and
before the left brace in both the prototype and the definition.
Example
In this example from a header file for a vector-like class, the capacity
and
empty
functions don't change the object, and therefore
are declared const
. clear
may change
the object and therefore can not be declared const
.
int capacity() const; // max size before reallocation
void clear(); // delete all items
bool empty() const; // true if contains no elements (size()==0)
const
can't be used for constructors and destructors
The purpose of a constructor is to initialize field values, so it must
change the object. Similarly for destructors.
Can overload with non-const
functions
There can be both const
and non-const
functions.
The compiler will choose the appropriate one to call depending on the
object they are being applied to. [Note: this seems like more of a
theoretical possibility rather than something that would ever be used.
Is there a common use for defining more than the const
version?]