const member functions
Member functions should be declared with the
const member functions can use
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-
A function can only be declared
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.
const keyword is placed after the function header and
before the left brace in both the prototype and the definition.
In this example from a header file for a vector-like class, the
empty functions don't change the object, and therefore
clear may change
the object and therefore can not be declared
int capacity() const; // max size before reallocation
void clear(); // delete all items
bool empty() const; // true if contains no elements (size()==0)
The purpose of a constructor is to initialize field values, so it must
change the object. Similarly for destructors.
const can't be used for constructors and destructors
Can overload with non-
There can be both
const and non-
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