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?
Will
AandBbe able to have different values forthing?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With