Static Members
Static data members
class Account {
static int count; // one shared variable for ALL Account objects
};
int Account::count = 0; // definition in one .cpp file (pre-C++17)
C++17 inline static ✅
class Account {
static inline int count = 0; // defined right here
static constexpr double RATE = 0.05; // compile-time constant
};
Static member functions
static int total_accounts() { return count; }
Account::total_accounts(); // called on the class, no object needed
- No
thispointer - Can only access static members directly (no object to read normal members from)
Accessing static members
Account::count (preferred) or obj.count (works but misleading).
Common uses
- Counters: number of objects created/alive
- ID generators:
next_id++ - Shared configuration: interest rate, tax rate
- Factory functions:
static Account create_savings(...) - Constants:
static constexpr int MAX_USERS = 100;
Static vs global
Static members are like globals but scoped to the class and can be private — much better encapsulation.
Lifetime
Static members exist before main runs and live until the program ends, even if no object is ever created.
⚠️ Static initialization order
Static/global variables in different .cpp files are initialized in an unspecified order. Avoid having one depend on another (use a function with a local static instead).
Example
#include <iostream>
#include <string>
class Account {
public:
explicit Account(std::string owner) : owner_(std::move(owner)), id_(next_id_++) { ++alive_; }
~Account() { --alive_; }
static int alive() { return alive_; } // no object needed
static void set_rate(double r) { if (r >= 0 && r < 0.2) rate_ = r; }
static Account savings_for(const std::string& owner) { return Account(owner + " (savings)"); }
double yearly_interest(double balance) const { return balance * rate_; }
void print() const { std::cout << "#" << id_ << " " << owner_ << '\n'; }
static constexpr int MAX_PER_USER = 5;
private:
std::string owner_;
int id_;
static inline int next_id_ = 1;
static inline int alive_ = 0;
static inline double rate_ = 0.05;
};
int main() {
std::cout << "Accounts before any created: " << Account::alive() << '\n';
Account a("Asha");
Account b("Ravi");
{
Account temp("Temporary");
temp.print();
std::cout << "Alive inside block: " << Account::alive() << '\n';
}
std::cout << "Alive after block: " << Account::alive() << '\n';
Account s = Account::savings_for("Asha");
s.print();
std::cout << "Interest on 10000 at default rate: " << a.yearly_interest(10000) << '\n';
Account::set_rate(0.07); // affects every account
std::cout << "After rate change, b earns: " << b.yearly_interest(10000) << '\n';
std::cout << "Max accounts per user: " << Account::MAX_PER_USER << '\n';
return 0;
}
/* Output:
Accounts before any created: 0
#3 Temporary
Alive inside block: 3
Alive after block: 2
#4 Asha (savings)
Interest on 10000 at default rate: 500
After rate change, b earns: 700
Max accounts per user: 5
*/