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:
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 guide to sharing values between objects using static class variables and functions