Unit 14: Static

  1. Member variables belong to separate instances
  2. Static methods
  3. Static variables
  4. Using static variables

  5. Example code and additional resources

This week's stuff:

Member variables belong to separate instances

In the context of classes and their variables, the variables we've been working with so far are member variables. When a new object is instantiated, each object has its own version of these variables:

Cat cat1;
Cat cat2;

cat1.name = "Kabe";
cat2.name = "Luna";

cat1 and cat2 both have variables called name, but cat1's name is different from cat2's name - in memory address, and in value.

We can also declare static functions and variables within a class. These static items don't belong to an instance of an object - they belong to the class.

Static methods

When a class has a function declared as static, then that function can be called directly via the class itself, though it can also be called via an object.


class Example
  static void Display();


void Example::Display()
  cout << "HI" << endl;


// Calling via the class

// Calling via an object
Example e;

Static variables

Static variables are variables that belong to the entire class. What this means is that each instance of the object share the same variable - it's the same memory address, the same value. If the value is changed by one instance, that change is reflected across all instances.

Cat class with a static cat count:

class Cat
  Cat( string name );
  void Display();
  string m_name;
  static int s_catCount;

Cat constructor adds to cat count when called:

Cat::Cat( string name )
  m_name = name;

Each time a new Cat is instantiated the s_catCount goes up by 1.

Using static variables

When creating a static variable, in the class declaration these variables need to be marked with the static keyword:

static int s_counter;

In the C++ file, the static variable needs to be defined, outside of any functions, like this:

int Kitten::s_counter = 0;

Every time a constructor is run, it adds to the count. Every time a destructor is run, it subtracts from the count.

Example code and additional resources

Example code: (repository)