Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Friend for nested structure in C++

Tags:

c++

struct

nested

I know Thinking in C++ by Bruce Eckel is not a reference book but I found a strange paragraph and I don't understand if it's still applicable today:

Making a structure nested doesn’t automatically give it access to private members. To accomplish this, you must follow a particular form: first, declare (without defining) the nested structure, then declare it as a friend, and finally define the structure. The structure definition must be separate from the friend declaration, otherwise it would be seen by the compiler as a non-member.

I actually 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 still a need to declare a nested structure friend in order to modify the private members of the base class?

like image 549
Mihai Neacsu Avatar asked Jan 16 '23 08:01

Mihai Neacsu


1 Answers

That quote is wrong. A nested inner class-type 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 that version of the standard. In C++03 and C++11 the quote doesn't apply.

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. The members of an enclosing class have no special access to members of a nested class; the usual access rules (Clause 11) shall be obeyed.

like image 193
Luchian Grigore Avatar answered Jan 25 '23 19:01

Luchian Grigore