Skip to content
  • Static Members · C++

Static Members

LearnViaNotes @learnvianotes· 2 min read

A static member belongs to the class itself, not to any object: one shared copy of a data member, and member functions callable without an object.

Static data and functions

C++
#include <iostream>
#include <string>

class User {
public:
    explicit User(std::string name) : name_(std::move(name)), id_(++created_) { ++alive_; }
    ~User() { --alive_; }
    User(const User&) = delete;

    static int alive() { return alive_; }       // no `this`: can only touch static members
    int id() const { return id_; }

    static constexpr int kMaxNameLength = 32;    // compile-time constant
private:
    std::string name_;
    int id_;
    inline static int created_ = 0;              // C++17: define in-class with `inline`
    static int alive_;                           // classic: declared here…
};
int User::alive_ = 0;                            // …defined once in a .cpp

int main() {
    User a("ada");
    {
        User b("bob");
        std::cout << User::alive() << ' ' << b.id() << '\n';
    }
    User c("cy");
    std::cout << User::alive() << ' ' << c.id() << ' ' << User::kMaxNameLength << '\n';
}
Output
2 2
2 3 32
Non-static memberStatic member
Belongs toEach objectThe class (one copy)
Accessobj.mClass::m (or obj.m)
Has thisYesNo — can't use non-static members directly
Can be virtual / constYesNo

Singleton & factory patterns

C++
#include <iostream>
#include <string>

class Logger {
public:
    static Logger& instance() {            // Meyers singleton: thread-safe lazy init (C++11)
        static Logger logger;
        return logger;
    }
    void log(const std::string& msg) { std::cout << ++count_ << ": " << msg << '\n'; }
    Logger(const Logger&) = delete;
    Logger& operator=(const Logger&) = delete;
private:
    Logger() = default;                    // nobody else can construct one
    int count_ = 0;
};

class Temperature {
    double kelvin_;
    explicit Temperature(double k) : kelvin_(k) {}
public:
    static Temperature fromCelsius(double c) { return Temperature(c + 273.15); }   // named constructors
    static Temperature fromKelvin(double k)  { return Temperature(k); }
    double kelvin() const { return kelvin_; }
};

int main() {
    Logger::instance().log("start");
    Logger::instance().log("again");
    std::cout << Temperature::fromCelsius(25).kelvin() << '\n';
}
Output
1: start
2: again
298.15

The many meanings of static

WhereMeaning
Class memberShared by all objects
Local variableKeeps its value between calls; initialised once
Namespace-scope function/variableInternal linkage — private to this .cpp (prefer an anonymous namespace)

Why can't a static member function be const or virtual?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report