C++ Static Keyword: Ultimate Guide
By The Cherno | Full Playlist π
1. Static Outside Classes/Structs
π Key Idea: static gives variables/functions internal linkage (visible only within their translation unit/file).
Example 1: Static Variables
// File1.cpp
static int s_Data = 5; // Only visible in File1.cpp
// File2.cpp
int s_Data = 10; // No conflict!
// Main.cpp
extern int s_Data; // Refers to File2.cpp's s_Data
int main() {
std::cout << s_Data; // Output: 10
}
Example 2: Static Functions
// Math.cpp
static void Log(const std::string& msg) { // File-specific
std::cout << "[LOG]: " << msg << std::endl;
}
// Main.cpp
void Log(const std::string& msg) { // Separate function
std::cerr << "[ERROR]: " << msg << std::endl;
}
Why Use?
- Avoid linker errors from duplicate symbols.
- Hide helper functions from other files.
2. Static Inside Classes/Structs
π Key Idea: Shared across all instances (only 1 memory location).
Example 1: Static Variable
class Player {
public:
static int s_Count; // Declaration
Player() { s_Count++; }
};
int Player::s_Count = 0; // Required definition
int main() {
Player p1, p2;
std::cout << Player::s_Count; // Output: 2
}
Example 2: Static Method
class Math {
public:
static double Square(double x) { return x*x; }
};
int main() {
std::cout << Math::Square(5); // Output: 25
}
Rules:
- Canβt access non-static members.
- No
thispointer.
3. Static in Headers (π Pitfalls)
Never do this:
// Config.h
static int s_Level = 1; // Creates SEPARATE copies in each .cpp file!
Solution: Use extern:
// Config.h
extern int s_Level; // Declaration
// Config.cpp
int s_Level = 1; // Single source of truth
4. Best Practices
- Minimize Global Statics: Use within classes for encapsulation.
- Initialize Class Statics Outside:
// Logger.h class Logger { public: static int s_Level; }; // Logger.cpp int Logger::s_Level = 2; - Use for Utility Functions:
class StringUtils { public: static std::string Trim(const std::string& s); };
5. Real-World Use Cases
Case 1: Singleton Pattern
class App {
private:
static App* s_Instance;
public:
static App& Get() { return *s_Instance; }
};
App* App::s_Instance = nullptr; // Definition
Case 2: Performance Counters
class Texture {
public:
static int s_LoadedTextures;
Texture() { s_LoadedTextures++; }
};
int Texture::s_LoadedTextures = 0;
Cheat Sheet
| Scenario | Syntax | Linkage |
|ββββββββββ|ββββββββββββββ|βββββββ-|
| File-local variable | static int var; | Internal |
| Shared class variable | static int var; + external definition | External (class) |
| Utility method | static void Helper(); | No instance needed |
Timestamps Reference
| Full Video π | Playlist: C++ Series |
π‘ Pro Tip: Use static to reduce global namespace clutter and manage shared resources efficiently!
