Review of Important C++ Concepts
- Basic C++ Concepts:
- Class variables versus instance variables
- Class variables are declared in the class definition using the static keyword prefix.
- While each instance of a class has its own copy of instance variables, all instances
of a class share the same single copy of class variables.
- Class methods versus instance methods
- Class methods are declared in the class definition using the static keyword prefix.
- Class methods are not associated with any specific instance. As a result, note that the built-in
identifier this is not declared in class methods, and instance variables cannot be
accessed inside a class method unless the access is qualified using a specific instance of
the class.
- Uses of class variables and class methods in our framework:
- One important use of class variables in our framework is to ensure that common
view data and other viewing-related parameters are used by all ModelView instances. See, for
example, mcRegionOfInterest in class ModelView. You will also see other uses; for example,
some example programs define and use a
serial number to distinguish between multiple ModelView instances.
- Class methods are needed for at least three major purposes:
-
Share implementations of important common operations that depend only on data in shared class variables;
e.g., view-related computations. See, for example, ModelView::compute2DScaleTrans.
- Facilitate event handling by mapping a call to a class method into an instance method of a class.
The
Controller
will need to do this when handling events. Recall that neither OpenGL
nor the GLFW window interface is object-oriented. The approach used by window managers like GLFW
is to invoke user-registered callback functions written in C (i.e., not C++ instance methods)
to handle events. Since
C++ class methods "look like" ordinary C functions, they can be registered as callback functions.
You can see examples of this if you study the implementation of class GLFWController (e.g.,
methods GLFWController::charCB or GLFWController::keyboardCB; note that
curController is a class variable in class Controller). However,
unless you create your own Controller subclass, you will not likely need to do this in your code.
- Some types of general operations associated with a class do not depend exclusively on specific instance
variables of any one instance. Typically methods that implement such operations are written as class
methods. One specific type of method like this that we will encounter is called a "factory method".
The job of factory methods is to create an instance of a class in situations when use of an ordinary
constructor is either not possible or not desirable.
Bottom Line
When studying class definitions in our framework, pay attention to whether variables and methods are declared as
static. Be sure you understand why any given variable or method is or is not declared that way, and be
aware of how that declaration affects how it is used.