Ashot
Ashot

Reputation: 10979

Private static member in base class

#include <iostream>
#include <string>

class Base
{
    static std::string s;
};

template<typename T>
class Derived
    : Base
{
public:
    Derived()
    {
        std::cout << s << std::endl;
    }
};

std::string Base::s = "some_text";    

int main()
{
    Derived<int> obj;
}

This programs compiles and runs normally. static variable s is private in base class that is inherited privately. How is Derived class accessing it?

If Derived class is not template, compiler complains about accessing private variable.

[aminasya@amy-aminasya-lnx c++]$ g++ --version
g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Upvotes: 17

Views: 874

Answers (3)

Nir Friedman
Nir Friedman

Reputation: 17724

I think this is a compiler bug, as this compiles with gcc but not clang, for me.

Edit: as an additional data point, this bug does not seem to have been fixed, as I can reproduce in gcc 4.9.2 and 5.1.

Upvotes: 5

Barry
Barry

Reputation: 304142

This is definitely a GCC bug, equivalent to GCC Bug 58740:

class A {
    static int p;
};
int A::p = 0;
template<int=0>
struct B : A {
    B() {(void)p;}
};
int main() {
    B<>();
}

The bug is still open, and this code still compiles on 5.1. GCC has issues with template member access, this is just another such example.

Upvotes: 17

user2249683
user2249683

Reputation:

It's a bug in g++ 4.8.4. The code compiles, only if Derived is a template and the member is static.

Tests:

  • template static compiles
  • no template static fails
  • template not static fails
  • no template not static fails

Upvotes: 3

Related Questions