C/C++ Arena

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

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 task

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.

Challenge 2

Write a class Player that knows how many players are currently alive: the constructor adds one, the destructor removes one, and static int alive() returns the count.

Challenge 3

Write a class Config with a static constexpr int max_players = 10 and a static bool valid_team_size(int n) that accepts 1 up to half of max_players. Both are used through the class name, without creating an object.

Previous: const member functions Next: Challenge: a Clock class