Static Class Variables and Functions

Static vs Non-Static Variables

What are the primary differences between static and non-static variables?

Abstract art representing computer programming

In C++, the primary difference between static and non-static variables lies in their lifetime and scope.

Non-static variables are instance variables, meaning each instance of a class has its own copy of these variables. For example, if you have a Vampire class with a Health variable, each Vampire object will have its own Health:

#include <string>

class Vampire {
public:
  int Health{100};
};

int main() {
  Vampire A;
  A.Health = 50;

  Vampire B;
  B.Health = 200;
}

In this example, Vampire A has a Health of 50, while Vampire B has a Health of 200. Each instance operates independently with its own copy of Health.

Static variables, on the other hand, are shared among all instances of a class. They belong to the class itself, not to any particular instance. When a variable is declared as static, all instances of the class share the same memory location for that variable:

#include <iostream>

class Vampire {
 public:
  static inline std::string Faction{"Undead"};
};

int main() {
  Vampire A;
  Vampire B;
  if (&A.Faction == &B.Faction) {
    std::cout << "They're the same";
  }
}
They're the same

Here, Faction is static, meaning it is shared by all Vampire objects. Changing Faction for one Vampire changes it for all:

#include <iostream>

class Vampire {
 public:
  static inline std::string Faction{"Undead"};
};

int main() {
  Vampire A;
  Vampire B;
  A.Faction = "Demonic";
  std::cout << B.Faction;  
}
Demonic

In summary:

  • Non-static variables: unique to each instance, different instances can have different values.
  • Static variables: shared across all instances, one value for the entire class.

Understanding the difference helps you decide whether a variable should be unique to each instance or shared among all instances.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved