Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing private nested class

I made this simple class, which still is playing with my mind:

class A {
private:
    class B {};

public:
    B getB() {
        return B();
    };
};

As of C++03, this class compiles fine, but there is just no nice looking way to assign the result of getB() to an lvalue, in the sense that:

A::B b = A().getB();

Does not compile.

I got it by using an intermediate template, in this fashion:

template <typename T>
struct HideType {
    typedef T type;
};

HideType<A::B>::type b = A().getB();

But this looks just terrible, for this simple task of getting an A::B lvalue variable.

This is not true anymore as of C++11, or at least it is not with gcc. This code is still not valid:

A::B b = A().getB();

But this is valid:

auto b = A().getB();

Is there a loophole in the standard respect to this?

like image 671
Samuel Navarro Lou Avatar asked Dec 13 '15 13:12

Samuel Navarro Lou


People also ask

How do I access private nested classes?

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.

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.

Can nested classes access private members C#?

A nested type has access to all of the members that are accessible to its containing type. It can access private and protected members of the containing type, including any inherited protected members.

Can inner class access private variables Java?

It can access any private instance variable of the outer class. Like any other instance variable, we can have access modifier private, protected, public, and default modifier. Like class, an interface can also be nested and can have access specifiers.


1 Answers

From Standard, Clause 11 (Member access control):

A member of a class can be
— private; that is, its name can be used only by members and friends of the class in which it is declared.
— protected; that is, its name can be used only by members and friends of the class in which it is declared, by classes derived from that class, and by their friends (see 11.4).
— public; that is, its name can be used anywhere without access restriction.

So access control is applied to names.

In

auto b = A().getB();

you don't use private names, therefore it's legal, according to Standard

like image 84
Victor Dyachenko Avatar answered Oct 05 '22 00:10

Victor Dyachenko