struct A { private: static int x; }; int A::x = 0; struct B: public A { void foo() { std::cout << x; } }; 

Why gives an error:

[Error] 'int A :: x' is private

?

  • 2
    Because private?) - Alexey Sarovsky
  • You do not have the problem of inheritance, but initialization int A::x = 0; Initialize your variable in structure A - Alexey Sarovsky
  • @AlekseySarovsky, the problem here is not initialization. Static class fields must be defined outside the class. The problem is accessing the member x from a class B method. In class B x member is not available for direct conversion, since defined in class A in the private section. The correct answer from @Harry is below. - aleks.andr

1 answer 1

Because a private member is available only to the class and friends.

In order to be accessible from B , it must be at least protected .