Marking a variable as static
in C++ affects its memory allocation by changing its storage duration and scope.
For example:
#include <string>
class Vampire {
public:
int Health{100};
};
int main() {
Vampire A;
Vampire B;
// A and B have separate memory for Health
}
Here, A
and B
each have their own Health
variable, stored separately in memory.
For example:
#include <iostream>
#include <string>
class Vampire {
public:
static inline std::string Faction{"Undead"};
};
int main() {
Vampire A;
Vampire B;
// A and B share the same memory for Faction
}
In this case, Faction
is allocated once and shared by all instances of Vampire
.
::
.#include <iostream>
#include <string>
class Vampire {
public:
static inline std::string Faction{"Undead"};
};
int main() {
std::cout << Vampire::Faction << "\n";
Vampire::Faction = "Demonic";
std::cout << Vampire::Faction << "\n";
}
Undead
Demonic
In summary, marking a variable as static
centralizes memory usage for shared data, providing efficient memory management and consistent data access across all instances of the 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