I have the following code
class A
{
private:
class B
{
public:
void f()
{
printf("Test");
}
};
public:
B g()
{
return B();
}
};
int main()
{
A a;
A::B b; // Compilation error C2248
A::B b1 = a.g(); //Compilation error C2248
auto b2 = a.g(); // OK
a.g(); // OK
b2.f(); // OK. Output is "Test"
}
As you can see I have class A and private nested class B. Without using auto I can't create instance of A::B outside A, but with auto I can. Can somebody explain what wrong here? I use VC++ 12.0, 13.0, 14.0 (always same behavior)
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.
To create an instance of nested class, one should have access to its declaration. It can be instantiated only from outer class or from a friend of that class. 2 Member functions and static data members of a nested class can be defined in a namespace scope enclosing the definition of their class.
So, yes; an object of type Outer::Inner can access the member variable var of an object of type Outer .
There are two types of nested classes non-static and static nested classes. The non-static nested classes are also known as inner classes.
The type B
is accessible only to A
and friends of A
, which means that other code cannot refer to it. On the other hand template type deduction works even for private types, which is needed if you ever wanted to use your private type in any form of template inside A
's code.
The auto
feature is based on template type deduction and follows the same rules, allowing for the call auto b2 = a.g();
.
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