C++
Summary - Static members
Combine static members, methods and const to write a MathConstants class.
Summary - Static members
In this group you learned about static members. A static member variable is shared across all instances; its definition goes outside the class. A static method is called without an instance and only accesses static members.
static const integer constants can be initialized inside the class. With C++17 inline static, every type can be defined inside the class without an outside definition. static_assert checks conditions at compile time and prevents faulty code from compiling. Together these tools enable safe and reusable class design.
static_assert and static const together
In this summary let us combine two tools: you can define a constant with static const and verify it at compile time with static_assert.
For example, in a Bank class you can keep inline static int accountCount = 0; and increment it for each new account. In the same code, static_assert(sizeof(int) >= 2, ...) guarantees the type size. This is both safe and suitable for header-only design.
Exercise Add an inline static counter to the Bank class
Define a Bank class. Under public: add inline static int accountCount = 0;. Increment accountCount++ in the constructor. Under public: add static int getAccountCount() with body return accountCount;. In main create three Bank objects and write std::cout << Bank::getAccountCount();.
Show example solution
#include <iostream>
class Bank {
public:
inline static int accountCount = 0;
static int getAccountCount() { return accountCount; }
Bank() { accountCount++; }
};
int main() {
Bank b1;
Bank b2;
Bank b3;
std::cout << Bank::getAccountCount();
return 0;
}
Exercise Secure the Bank code with static_assert
Inside main write static_assert(sizeof(int) >= 2, "int at least 2 bytes");. Then print "Safe" with std::cout to show compilation succeeded.
Show example solution
#include <iostream>
int main() {
static_assert(sizeof(int) >= 2, "int at least 2 bytes");
std::cout << "Safe";
return 0;
}
Test yourself
-
What does inline static int count = 0; provide?
class Player { public: inline static int count = 0; };
- In-class definition without outside definition
- Performs a runtime check
- Hides the method
- Requires creating an instance
Show answer
In-class definition without outside definition — inline static provides in-class initialization without an outside definition.
-
Match each concept to its purpose
- static int count;
- Shared member
- static int get()
- Call without instance
- inline static
- C++17 no outside definition
- static_assert
- Compile-time check
Next lesson: Polymorphism basics