12

Are static fields inherited?

 3 years ago
source link: https://www.codesd.com/item/are-static-fields-inherited.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Are static fields inherited?

advertisements

When static members are inherited, are they static for the entire hierarchy, or just that class, i.e.:

class SomeClass
{
public:
    SomeClass(){total++;}
    static int total;
};

class SomeDerivedClass: public SomeClass
{
public:
    SomeDerivedClass(){total++;}
};

int main()
{
    SomeClass A;
    SomeClass B;
    SomeDerivedClass C;
    return 0;
}

would total be 3 in all three instances, or would it be 2 for SomeClass and 1 for SomeDerivedClass?


3 in all cases, since the static int total inherited by SomeDerivedClass is exactly the one in SomeClass, not a distinct variable.

Edit: actually 4 in all cases, as @ejames spotted and pointed out in his answer, which see.

Edit: the code in the second question is missing the int in both cases, but adding it makes it OK, i.e.:

class A
{
public:
    static int MaxHP;
};
int A::MaxHP = 23;

class Cat: A
{
public:
    static const int MaxHP = 100;
};

works fine and with different values for A::MaxHP and Cat::MaxHP -- in this case the subclass is "not inheriting" the static from the base class, since, so to speak, it's "hiding" it with its own homonymous one.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK