1

I have been trying to understand this and to find some information about definition of struct type inside a class (for C++). However, I have not find yet any good clarification to my actual doubt. In case we have the following definition

namespace MyOuterNamespace {
  namespace MyInnerNamespace {
    class MyClass {
      struct MyStruct {
        int myVar;
      };
      MyStruct m_MyStruct;
    };
  }
}

Here in this sample code the m_MyStruct is a private member, so it cannot be access from the outside. However the struct definition is accessible and we can declare a struct variable of this type in any place with

MyOuterNamespace::MyInnterNamespace::MyClass::MyStruct outsideStruct;

What is the principal to make this possible. If the structure is defined as a type in the private section of the class, why is possible to use it from outside? Is this working only as "namespace" for the structure definition. It is not actually hidden as the struct variable.

I have found out several articles but maybe this answer from a similar thread is actually answering and giving the principal of how this is understood by the language: Nested structures

Can anybody confirm this or provide a better explanation?

[EDIT] You can do this for public definitions but for private you face the expected visibility error.

Thanks!

  • 2
    No, you cannot access an inner type of a class. Trying to compile the above declaration of `outsideStruct` gives "error: 'MyStruct' is a private member of 'MyOuterNamespace::MyInnterNamespace::MyClass'". – lubgr Aug 07 '20 at 08:54
  • 1
    _"However the struct definition is accessible and we can declare a struct variable of this type"_ - No you, can't! Did you compile this? If yes, how? Proof: http://coliru.stacked-crooked.com/a/accea178513b7692 – Lukas-T Aug 07 '20 at 08:54
  • The only compiler I've found that compiles this was Intels ICC (while complaing with warnings)-- gcc, llvm and msvc all (rightfully) refuse with error messages: https://godbolt.org/z/3qWhcx – radioflash Aug 07 '20 at 09:24
  • Thank you for the replies. Yes, after all this was not compiling. The struct definition was inside a public section and not in private after all. Anyway I will leave this question here for reference. Thanks you all! – Miroslav Stoychev Aug 07 '20 at 09:52

1 Answers1

0

Private means private. No less, no more. Just make note that C++ is not object-oriented language, it just supports use of classes. Thus, in fact, encapsulation can be severed using raw pointers having information about fields sizes and declaration order. Using double colons for namespacing is a facilitation here.

eddiszszu
  • 36
  • 3