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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With