Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 347
Ashot Avatar asked Jul 08 '15 16:07

Ashot


People also ask

Can you access private members of a base class?

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.

Can a static class have private members?

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.

Can a derived class access static members of a base class?

So long as the variable is private you can't access it in the derived class.

Can private members of a base class are inheritable?

Yes, Private members of base class are inherited in derived class..But objects of derived class have no access to use or modify it..


2 Answers

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.

like image 197
Barry Avatar answered Oct 25 '22 03:10

Barry


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.

like image 34
Nir Friedman Avatar answered Oct 25 '22 03:10

Nir Friedman