Yves
Yves

Reputation: 12391

Initialize the protected static member from the subclass

I want to know if it's possible to initialize a protected static member from the subclass.
For example,

// head file
class Test
{
protected:
    static int i;
};
class Test2 : public Test{};

//cpp file
#include "headfile.h"
int Test2::i = 1;

As you see, when I initialize this static member (i), I use the subclass name (Test2).
To my surprise, I tested this code with visual studio 2013 and it worked without error. But if I tried it with Netbeans(gcc11) under Linux and I got an hint error:
unable to resolve the identifier i
Then I compiled it, the error message is:
error: ISO C++ does not permit ‘Test::i’ to be defined as ‘Test2::i’ [-fpermissive]

Now if I change the protected into public for the static int i in the class Test, the error will disappear.

I am confused... This is my first time that I found two different results with gcc and vs.

Upvotes: 4

Views: 1140

Answers (1)

Potatoswatter
Potatoswatter

Reputation: 137890

The definition violates C++14 [class.static.data] §9.4.2/2. Emphasis mine:

In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator.

A more recent version of GCC (on Coliru) behaves the same regardless of the qualifier. You can defeat the error on GCC with -fpermissive, but note that you're still only defining one object, belonging to the base class.

Upvotes: 4

Related Questions