What is a static constructor?

C++ doesn’t have static constructors but you can emulate them using a static instance of a nested class.

class has_static_constructor {
    friend class constructor;

    struct constructor {
        constructor() { /* do some constructing here … */ }
    };

    static constructor cons;
};

// C++ needs to define static members externally.
has_static_constructor::constructor has_static_constructor::cons;

Leave a Comment