2

I have this example code (in a file named A.cpp):

class O {
private:
    struct S {
        int i;
        int j;
    };

    static struct S s;
};

O::S s { 0, 1 };

I compile with g++ -c -std=c++11 A.cpp from the command line on my Mac and I get the following error:

A.cpp:11:4: error: 'S' is a private member of 'O'
O::S s { 0, 1 };
   ^
A.cpp:3:9: note: declared private here
        struct S {
               ^
1 error generated

The problem originally arose in more complicate code on a linux machine with essentially the same error. (In the "real" code the class declaration is in a header instead of all in one file, but, again, the error is the same.)

This seems like it should work. Certainly S is declared private, as the message indicates, but it is only being used in the context of the private member variable s. What's wrong here and why?

EDIT: With regard to the claimed duplicate at How to initialize private static members in C++?, the apparent difference is the scope of the inner class rather than generically how to initialize a static member variable.

Brick
  • 3,998
  • 8
  • 27
  • 47
  • Possible duplicate of [How to initialize private static members in C++?](https://stackoverflow.com/questions/185844/how-to-initialize-private-static-members-in-c) – user657267 Apr 12 '18 at 20:21
  • @user657267 I had seen that question, but it didn't have the additional issue of the inner class, which was the ultimate problem. – Brick Apr 12 '18 at 20:24

2 Answers2

4

This line

O::S s { 0, 1 };

Attempts to define an object ::s of the type O::S. It's not a definition of the static member. That one will look like this:

O::S O::s { 0, 1 };
Brick
  • 3,998
  • 8
  • 27
  • 47
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
-1

S class is declared in the private section of O so code outside the class O can't access it. Specifically, you can't instantiate class S outside class O since that would constitute accessing a private declaration.

If you want to be able to create instances if S outside class O, you should declare it public.

shoosh
  • 76,898
  • 55
  • 205
  • 325