Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a static member inside a nested class have static duration for the enclosing class?

If I have nested classes, and these nested classes have static members, will those members still be static for the enclosing class? For example, if I have

class Enclosing {
public:
    Enclosing();
private:
    class Nested {
    public:
        Nested();
    private:
        static int thing;
    };
};

If I do

auto A = Enclosing();
auto B = Enclosing();

Will A and B be able to have different values for thing?

like image 742
Aposhian Avatar asked Jan 02 '26 06:01

Aposhian


1 Answers

Will A and B be able to have different values for thing?

No they won't have different values. All instances will see the same value for thing; the nesting of the class has no impact here.

static member variables are "associated with the class" (i.e. over non-static members that are associated with the instances of the class). From cppreference;

Static data members are not associated with any object. They exist even if no objects of the class have been defined. If the static member is declared thread_local (since C++11), there is one such object per thread. Otherwise, there is only one instance of the static data member in the entire program, with static storage duration.

Live sample.

like image 162
Niall Avatar answered Jan 05 '26 19:01

Niall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!