Game Development Reference
In-Depth Information
Listing 9-3. A static Member Variable
class StaticCounter
{
private:
static int m_counter;
public:
void IncrementCounter()
{
++m_counter;
}
void Print()
{
std::cout << m_counter << std::endl;
}
};
int StaticCounter::m_counter = 0;
Using the static keyword on a member variable has a similar effect as using it on a local variable.
The variable will be created in static memory rather than within the memory space for the object
itself. You should pay special attention to the final line of this listing. Member variables that we
declare to be static must be defined and this usually occurs in the source file that accompanies
a header file for the class. A clear example of this is shown in the source code sample that
accompanies this chapter and can be downloaded from this topic's accompanying web site:
http://www.apress.com/9781430264576 . This causes all objects created from this class type to share
the same static variable, which in Listing 9-4 is the m_counter variable. The source code in Listing
9-4 shows how we can call these functions.
Listing 9-4. Using the StaticCounter Class
StaticCounter counter1;
counter1.Print();
counter1.IncrementCounter();
counter1.Print();
StaticCounter counter2;
counter2.Print();
counter2.IncrementCounter();
counter2.Print();
These lines of code in a program would output 0, 1, 1, then 2. This happens because both counter1
and counter2 are sharing the same m_counter variable. Another way you could see this in action
would be to look at the address of the m_counter variable. Listing 9-5 shows how you can do this.
Listing 9-5. Getting the Address of m_counter
void Print()
{
std::cout << m_counter << std::endl;
int* address = &m_counter;
}
Search WWH ::




Custom Search