Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance of private nested class c++ [duplicate]

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)

like image 933
Dmitry Avatar asked Dec 19 '14 20:12

Dmitry


People also ask

Can nested classes access private members?

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.

How do I create an instance of a nested class in C++?

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.

Does inner class have access private variables?

So, yes; an object of type Outer::Inner can access the member variable var of an object of type Outer .

What are the two types of nested classes?

There are two types of nested classes non-static and static nested classes. The non-static nested classes are also known as inner classes.


1 Answers

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();.

like image 95
David Rodríguez - dribeas Avatar answered Sep 21 '22 12:09

David Rodríguez - dribeas