Static Class Variables and Functions

Combining Static and Non-Static Variables

Can we have both static and non-static variables in the same class? How do they interact?

Abstract art representing computer programming

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:

  • Non-static variables are accessed through instances of the class.
  • Static variables can be accessed through instances or directly through the class itself using the scope resolution operator ::.

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 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:

  • 125 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