Game Development Reference
In-Depth Information
Two More Keywords
Whereas
static
and
const
have several uses and will be common in your code, there are another
two keywords that make an appearance in C++ but don't have such obvious effects. The first is the
inline
keyword and the second is the
friend
keyword.
The inline Keyword
At different times in your programming journey you will have to consider different goals. Sometimes
you will need to write code that executes as quickly as possible and at others you will have to write
code that uses as little memory as possible. The
inline
keyword and inline member methods allow
us to ask the compiler to help us with this.
When you inline a method the compiler will skip the instructions it needs to call the method;
instead, the function body will be duplicated every time you call the method. This duplication of
instructions reduces the length of time it takes to call the method, but increases the amount of
memory used by duplicating the method throughout the code. For methods that are called many
times, this duplication could be significant. Listing 9-18 contained two functions,
GetCounter
and
IncrementCounter
.
The compiler will attempt to inline these methods because the definitions are contained within
the class definition. You could achieve the same thing explicitly by making the changes shown in
Listing 9-19.
Listing 9-19. The
inline
Keyword
class ConstantExample
{
private:
int m_counter;
mutable int m_countGets;
public:
ConstantExample() : m_counter(0), m_countGets(0) {}
int GetCounter() const;
void IncrementCounter();
};
inline int ConstantExample::GetCounter() const
{
++m_countGets;
return m_counter;
}
inline void ConstantExample::IncrementCounter()
{
++m_counter;
}