class private_object
{
private:
struct make_public;
friend struct make_public;
static void method1() {}
};
struct private_object::make_public
{
class nested_outer
{
void callFromOuter()
{ private_object::method1(); } // Should this be an error?
class nested_inner
{
void callFromInner()
{ private_object::method1(); } // How about this one?
};
};
};
This friendship issue came up when I was trying to port an open source project to compile under borland. According to parashift and two semi-related questions here and here, the above example should not be valid.
However, after testing it on seven different compilers1, only borland and dmc complained. This behavior surprised me because I wasn't expecting friendship to be transitive in nested classes.
So this raises a couple of questions:
1. tested on mingw-gcc 4.5.2, clang, borland c++ builder2007, digital mars, open watcom, visualc2010 and comeau online
In C++03, nested class cannot access private
and protected
members of enclosing class by default (see §11.8/1). But if you make them friend of the enclosing classs, then they can access them. But again nested class of nested class is still not friend of the outermost enclosing class, the nested class of the nested class cannot access private and protected members of the outermost enclosing class; it cannot even access the private and protected member of the immediate enclosing class, as noted earlier. What you're doing is that, hence that is not allowed.
The C++ Standard (2003) says in $11.8/1 [class.access.nest],
The members of a nested class have no special access to members of an enclosing class, nor to classes or functions that have granted friendship to an enclosing class; the usual access rules (clause 11) shall be obeyed. 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.
Example from the Standard itself:
class E
{
int x;
class B { };
class I
{
B b; // error: E::B is private
int y;
void f(E* p, int i)
{
p->x = i; // error: E::x is private
}
};
int g(I* p)
{
return p->y; // error: I::y is private
}
};
By the way, its a defect in the C++03 Standard. Since the nested class is a member, it should have access to private and protected members, just like any other member:
§9.2/1 (C++03):
Members of a class are data members, member functions (9.3), nested types… Nested types are classes (9.1, 9.7) and enumerations (7.2) defined in the class…
See this Defect Report :
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