Yes, you can have both static and non-static variables in the same class. They serve different purposes and interact in specific ways.
Static variables are shared across all instances of the class, while non-static variables are unique to each instance.
This means that each instance of the class will have its own copy of non-static variables, but there will be only one copy of each static variable, regardless of the number of instances.
Consider this example:
#include <iostream>
#include <string>
class Vampire {
public:
int Health{100};
static inline std::string Faction{"Undead"};
};
int main() {
Vampire A;
Vampire B;
A.Health = 50;
B.Health = 200;
A.Faction = "Demonic";
std::cout << "A's Health: " << A.Health << "\n";
std::cout << "B's Health: " << B.Health << "\n";
std::cout << "Faction: " << Vampire::Faction;
}
A's Health: 50
B's Health: 200
Faction: Demonic
In this example:
Health
is a non-static variable, so each Vampire
instance (A
and B
) has its own Health
.Faction
is a static variable, so it is shared across all instances. Changing Faction
through A
also changes it for B
.When you have both static and non-static variables in a class:
::
.For example, you can access Faction
directly using Vampire::Faction
:
#include <iostream>
#include <string>
class Vampire {
public:
int Health{100};
static inline std::string Faction{"Undead"};
};
int main() {
Vampire A;
Vampire B;
Vampire::Faction = "Demonic";
std::cout << "Faction: "
<< Vampire::Faction << "\n";
A.Health = 50;
B.Health = 200;
std::cout << "A's Health: " << A.Health << "\n";
std::cout << "B's Health: " << B.Health << "\n";
}
Faction: Demonic
A's Health: 50
B's Health: 200
Combining static and non-static variables allows you to maintain shared state and individual state within the same class.
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