Game Engine Architecture

(Ben Green) #1
121

3.2.4.1. Class-Static Members


As we’ve seen, the static keyword has many diff erent meanings depending
on context:


z When used at fi le scope, static means “restrict the visibility of this
variable or function so it can only be seen inside this .cpp fi le.”
z When used at function scope, static means “this variable is a global,
not an automatic, but it can only be seen inside this function.”
z When used inside a struct or class declaration, static means “this
variable is not a regular member variable, but instead acts just like a
global.”

Notice that when static is used inside a class declaration, it does not
control the visibility of the variable (as it does when used at fi le scope)—
rather, it diff erentiates between regular per-instance member variables
and per-class variables that act like globals. The visibility of a class-static
variable is determined by the use of public:, protected: or private:
keywords in the class declaration. Class-static variables are automatically
included within the namespace of the class or struct in which they are
declared. So the name of the class or struct must be used to disambigu-
ate the variable whenever it is used outside that class or struct (e.g.,
Foo::sVarName).
Like an extern declaration for a regular global variable, the declaration
of a class-static variable within a class allocates no memory. The memory for
the class-static variable must be defi ned in a .cpp fi le. For example:


foo.h


class Foo
{
public:
static F32 sClassStatic; // allocates no
// memory!
};

foo.cpp


F32 Foo::sClassStatic = -1.0f; // define memory and
// init

3.2.5. Object Layout in Memory


It’s useful to be able to visualize the memory layout of your classes and
structs. This is usually prett y straightforward—we can simply draw a box
for the struct or class, with horizontal lines separating data members. An


3.2. Data, Code, and Memory in C/C++

Free download pdf