17
#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.
Barry
  • 286,269
  • 29
  • 621
  • 977
Ashot
  • 10,807
  • 14
  • 66
  • 117
  • Which compiler? gcc, clang? – Nir Friedman Jul 08 '15 at 16:36
  • Reading this question, could someone explain why the compiler doesn't think the line 'std::string Base::s = "some_text";' is global access, so prohibited for a private variable? Has been some time since I used C++. – Jacques de Hooge Jul 08 '15 at 16:43
  • 1
    That's a definition, not a declaration. It's just initializing the string that was previous declared inside of Base; since it was declared inside Base it is a class static variable, and it is private since that is the default access level for class. – Nir Friedman Jul 08 '15 at 16:44
  • I think this is a compiler bug, as this compiles with gcc but not clang, for me. – Nir Friedman Jul 08 '15 at 16:46
  • GCC bug, clang and ICC reject this code. Note that GCC has many bugs when it comes to access specification control and templates... – peppe Jul 08 '15 at 16:47

3 Answers3

17

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.

Barry
  • 286,269
  • 29
  • 621
  • 977
5

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.

Nir Friedman
  • 17,108
  • 2
  • 44
  • 72
3

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