#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.
Private members of the base class cannot be used by the derived class unless friend declarations within the base class explicitly grant access to them.
Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.
So long as the variable is private you can't access it in the derived class.
Yes, Private members of base class are inherited in derived class..But objects of derived class have no access to use or modify it..
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With