cpp / intermediate
Snippet
Static Constants in Object Templates
The 'static constexpr' combination allows you to define class-level constants that are evaluated at compile time and shared across all instances.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
class PhysicsEngine {public:static constexpr double GRAVITY = 9.81;};int main() {double currentG = PhysicsEngine::GRAVITY;return 0;}
Breakdown
1
static constexpr double GRAVITY
Shared across all objects and guaranteed to be a compile-time constant.
2
PhysicsEngine::GRAVITY
Accessed via the class name without needing to instantiate the class.