Game Development Reference
In-Depth Information
Using static Member Methods
Listing 9-3 contained the IncrementCounter method, which we called on the counter1 and counter2
objects in Listing 9-5. This method was a standard method that relied on an existing object to
be usable. C++ also allows us to create static member methods that do not rely on an object to
be callable. Listing 9-6 shows an updated version of the StaticCounter class that uses a static
member method.
Listing 9-6. Using a static Member Method
class StaticCounterMethod
{
private:
static int m_counter;
public:
static void IncrementCounter()
{
++m_counter;
}
static void Print()
{
std::cout << m_counter << std::endl;
int* address = &m_counter;
}
};
int StaticCounterMethod::m_counter = 0;
You can see in Listing 9-6 that the only changes that we make to turn our methods into static
methods is to add the static keyword at the beginning of their method signature. Listing 9-7 shows
how you can use these static methods.
Listing 9-7. Using static Methods
StaticCounterMethod::Print();
StaticCounterMethod::IncrementCounter();
StaticCounterMethod::Print();
StaticCounterMethod::Print();
StaticCounterMethod::IncrementCounter();
StaticCounterMethod::Print();
You can see in Listing 9-7 that we can now call these static methods in a different way than
non- static methods. First you use the name of the class, which is followed by the scope resolution
operator ( :: ) and the name of the static function we would like to call. You have already used
the scope resolution operator when accessing variable and function names that exist inside of
namespaces. In this instance we are simply letting the compiler know that we'd like to access the
global variables or methods that are contained within the class.
 
Search WWH ::




Custom Search