Step 5 of 9
static members
Normally each object has its own copy of every data member. A static data member is different: there's exactly one copy, shared by the whole class, whether zero or a thousand objects exist. A static member function belongs to the class too, and is called without an object, as ClassName::function().
#include <iostream>
#include <string>
class Order {
public:
explicit Order(std::string item) : item_(item), number_(++next_number_) {}
int number() const { return number_; }
static int total() { return next_number_; }
private:
std::string item_;
int number_;
static inline int next_number_ = 0;
};
int main() {
std::cout << Order::total() << "\n";
Order a("pizza");
Order b("salad");
Order c("soup");
std::cout << a.number() << " " << c.number() << " " << Order::total() << "\n";
}
0
1 3 3
Reading it
static inline int next_number_ = 0;declares the shared counter.inline(C++17) allows initializing it right in the class; older code defines it separately in a.cppfile.- Each constructor does
++next_number_and stores the result in the object's ownnumber_, so every order gets the next number in sequence. Order::total()is static, so it can be called before anyOrderexists. A static member function has nothispointer, so it can only use static members.
When to use static members
Counters shared across instances, constants that belong to the class (static constexpr int max_size = 64;), and factory functions that create objects. Like global variables, mutable static data is shared state, so use it sparingly.
Your turn: write a class Grenade that counts how many have ever been created (static int created()), and gives each one an int id() const in creation order starting at 1.
Previous: const member functions Next: Challenge: a Clock class