Special Classes and Functions 533
15
Summary ..............................................................................................................
Today, you learned how to create static member variables in your class. Each class,
rather than each object, has one instance of the static member variable. It is possible to
access this member variable without an object of the class type by fully qualifying the
name, assuming you’ve declared the static member to have public access.
You learned that one use of static member variables is as counters across instances of the
class. Because they are not part of the object, the declaration of static member variables
does not allocate memory, and static member variables must be defined and initialized
outside the declaration of the class.
Static member functions are part of the class in the same way that static member vari-
ables are. They can be accessed without a particular object of the class and can be used
to access static member data. Static member functions cannot be used to access nonstatic
member data because they do not have the thispointer.
Because static member functions do not have a thispointer, they also cannot be made
const. constin a member function indicates that thisis const.
Today’s lesson also included one of the more complex topics in C++. You learned how to
declare and use pointers to functions and pointers to member functions. You saw how to
create arrays of these pointers and how to pass them to functions, and how to call the
functions whose pointers were stored in this way. You learned that this is not really a
great idea, and that object-oriented techniques should allow you to avoid this in almost
every situation.
Q&A ....................................................................................................................
Q Why use static data when I can use global data?
A Static data is scoped to the class. In this manner, static data is available only
through an object of the class, through an explicit call using the class name if they
are public, or by using a static member function. Static data is typed to the class
DOinvoke pointers to member functions
on a specific object of a class.
DOuse typedefto make pointer to
member function declarations easier to
read.
DON’Tuse pointer to member functions
when simpler solutions are possible.
DON’Tforget the parenthesis when
declaring a pointer to a function (versus
a function that returns a pointer).
DO DON’T