I have the following code:
class Base
{
private:
class NestedBase
{
public:
void Do() {}
};
public:
NestedBase nested;
};
int main()
{
Base b;
b.nested.Do(); // line A compiles
Base::NestedBase instance; // line B doesn't compile
}
NestedBase
class is a private nested class of Base
, so it seems natural that line B doesn't compile. But, on the other hand, variable b
has the public member nested
, and I can call its method Do()
from outside of Base
(as in line A). What are the precise rules that regulate access to the private nested class (or its members) in such case? What does the standard say on this?
Accessing the Private Members Write an inner class in it, return the private members from a method within the inner class, say, getValue(), and finally from another class (from which you want to access the private members) call the getValue() method of the inner class.
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
Probably not, since the Main method must be in a public class. Show activity on this post. Main() method is where application execution begin, so the reason you cannot compile your first class (with public static void Main() ) is because you already have Main method somewhere else in your application.
A nested class is a class that is declared in another class. The nested class is also a member variable of the enclosing class and has the same access rights as the other members. However, the member functions of the enclosing class have no special access to the members of a nested class.
According to the standard, $11.7/1 Nested classes [class.access.nest]:
A nested class is a member and as such has the same access rights as any other member.
So, it's quite simple. NestedBase
is a private
member of class Base
, so Base::NestedBase
can't be accessed in main()
.
b.nested.Do();
is fine because nested
and Do()
are both public
members. The fact that NestedBase
is a private
nested class of Base
doesn't matter, it's irrelevant here.
Type name NestedBase
is a private member of the class.
class Base
{
private:
class NestedBase
{
public:
void Do() {}
};
//...
So you can not explicitly access it outside the class where the name is declared.
But you can access the name implicitly the following way:)
decltype( Base::nested) instance;
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