Friend for nested structure in C ++

I know Bruce Eckel's C ++ Thinking is not a reference, but I found a strange paragraph, and I don’t understand, it applies today:

Creating a nested structure does not automatically give private members access to it. To achieve this, you must follow a specific form: first, declare (without definition) a nested structure, then declare it as a friend and, finally, define the structure. the definition of the structure must be separated from the declaration of the friend, otherwise it would be seen by the compiler as non-member.

I really tried this without declaring the nested structure as a friend, and it worked:

struct myStruct{ private: int bar; public: struct nestedStruct{ void foo(myStruct *); }a; }; void myStruct::nestedStruct::foo(myStruct * p){ p->bar = 20; } 

Is there a need to declare each other a nested structure for changing private members of the base class?

+4
source share
1 answer

This quote is incorrect. A nested inner type class has access to all members (including private ) of the enclosing class type.

This was not the case in C ++ 98, and your edition probably refers to this version of the standard. In C ++ 03 and C ++ 11, the quote is not applicable.

11.7 Nested classes [class.access.nest]

1 A nested class is a member and, as such, has the same access rights as any other member. Members A private class does not have special access to members of a nested class; the usual access rules (clause 11) must be respected.

+6
source

Source: https://habr.com/ru/post/1439495/


All Articles