Are static fields inherited?

The answer is actually four in all cases, since the construction of SomeDerivedClass will cause the total to be incremented twice.

Here is a complete program (which I used to verify my answer):

#include <iostream>
#include <string>

using namespace std;

class SomeClass
{
    public:
        SomeClass() {total++;}
        static int total;
        void Print(string n) { cout << n << ".total = " << total << endl; }
};

int SomeClass::total = 0;

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

int main(int argc, char ** argv)
{
    SomeClass A;
    SomeClass B;
    SomeDerivedClass C;

    A.Print("A");
    B.Print("B");
    C.Print("C");

    return 0;
}

And the results:

A.total = 4
B.total = 4
C.total = 4

Leave a Comment