Homework 3 Mini Lesson: static
Class Members
There's a little bit of new syntax in this homework that we should give you a heads up about.
MORE syntax!!? I'll devour it!
Usually, when we define a class, we're thinking about the information that we want instances of the class to store. For example, in the Cow
class from this week's first lesson, each Cow
object stored an age and a number of spots.
But sometimes there is information we want to store that relates to the entire class (e.g., not one specific Cow
but all the Cow
s).
In C++, we indicate this property with the static
keyword:
// cow.hpp
class Cow {
...
// Static compile-time constants, declaration AND definition
static constexpr int MAX_LEGS = 4; // one (shared) constant for all cows
// Static variables and functions; declaration only (needs def in .cpp file)
static size_t totalCowsEver; // one (shared) variable for all cows
static void openCowWikipediaPage(); // function that doesn't require a cow
...
};
Compile-time constants, such as MAX_LEGS
, only need to be given in the class definition in the header file. But variables and functions are only declared in in the class definition—they still have to be defined in our source file.
// cow.cpp
size_t Cow::totalCowsEver = 0;
void Cow::openCowWikipediaPage() {
// Ask the system to open the Cow Wikipedia page in the browser...
}
Notice that we only need to say static
in the header file. When it comes to defining static
variables and functions, C++ already knows they're static and doesn't need or want us to repeat ourselves.
Using static
Members
Because our static members don't store/use any per-Cow
data, you don't need a Cow
object to use them. In other words, instead of saying bessie.MAX_LEGS
(which needs a Cow
, such as bessie
, to work) instead we just say Cow::
to get at our static members.
int main() {
std::cout << Cow::MAX_LEGS << std::endl;
std::cout << Cow::totalCowsEver << std::endl;
Cow::openCowWikipediaPage();
}
Things to Remember
- A
static
member is a property of the class, not an individual object. - If something is
constexpr
, you only need to declare and define it in the header; otherwise it needs a definition in the source file, too. - No matter how many objects are created (even 0!), there is exactly one copy of a
static
member and all instances of a class share it. - To access a
static
member from outside the class, we use the scope-resolution operator,::
, to specify that we want the variable that is contained within the class.
Homework 3 will involve some
static constexpr
members, so remember this syntax!
(When logged in, completion status appears here.)