Game Development Reference
In-Depth Information
Listing 9-16. A
const
Member Method
class ConstantExample
{
private:
int m_counter;
public:
ConstantExample() : m_counter(0) {}
int GetCounter() const { return m_counter; }
void IncrementCounter() { ++m_counter; }
};
You can create a
const
method by adding
const
to the end of the method signature. The implication
of this goes hand in hand with
const
variables. Listing 9-17 gives an example.
Listing 9-17. A
const
Reference
ConstantExample example;
const ConstantExample& constRefExample = example;
constRefExample.IncrementCounter();
constRefExample.GetCounter();
If you try to compile the code in Listing 9-17 you will receive an error. We cannot call
IncrementCounter
using the
const
reference, as it is not a constant member method. You also
cannot call non-
const
members on constant pointers or on constant variables.
You will receive a compile error if you try to alter any member variables in
const
member methods.
Listing 9-18 shows how we can use the
mutable
keyword to tell the compiler that a member variable
can be changed in
const
member methods.
Listing 9-18. The
mutable
Keyword
class ConstantExample
{
private:
int m_counter;
mutable int m_countGets;
public:
ConstantExample() : m_counter(0), m_countGets(0) {}
int GetCounter() const { ++m_countGets; return m_counter; }
void IncrementCounter() { ++m_counter; }
};
Listing 9-18 shows a good example of the
mutable
keyword. It is best used sparingly and usually
for debug information as the keyword technically goes against the normal usage of
const
member
methods. The code in Listing 9-18 allows us to count how many times the
GetCounter
method is
called even though is it a
const
member method and shouldn't be able to change any member
values.