Static Class Variables and Functions

Memory Allocation for Static Variables

How does marking a variable as static impact memory allocation?

Abstract art representing computer programming

Marking a variable as static in C++ affects its memory allocation by changing its storage duration and scope.

Non-Static Variables

  • Storage Duration: Automatic (local variables) or dynamic (heap allocation).
  • Scope: Limited to the instance of the class.
  • Memory Allocation: Each instance of the class gets its own memory allocation for non-static variables.

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.

Static Variables

  • Storage Duration: Static (exists for the lifetime of the program).
  • Scope: Shared among all instances of the class.
  • Memory Allocation: Only one allocation for the static variable, regardless of the number of instances.

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.

Impact on Memory Allocation

  • Efficiency: Static variables save memory when the same data is shared among all instances. Instead of each instance having its own copy, a single copy is shared.
  • Lifetime: Static variables persist for the lifetime of the program. They are allocated when the program starts and deallocated when the program ends.
  • Access: Static variables can be accessed without creating an instance of the class, using the class name and the scope resolution operator ::.
#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 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