C++ nested classes accessibility

前端 未结 4 677
清酒与你
清酒与你 2020-12-05 10:24

Given the following code without considering friendship between two classes:

class OutSideClass
{
...
public:
    int i_pub;
protected:
             


        
相关标签:
4条回答
  • 2020-12-05 10:29

    As @Nawaz points out, in C++03 nested classes do not have special access rights to members of the enclosing class. However, this limitation is easy to get around by declaring the nested class as a friend.

    class OutSideClass
    {
    ...
    
        class InSideClass
        {
            ...
        };
        friend class InSideClass;
    };
    
    0 讨论(0)
  • 2020-12-05 10:36

    All that nested classes do in C++ is put the inner class in the namespace of the outer class. To instantiate an instance of InSideClass from a member function of OutSideClass, I'd just do

    InSideClass *instance = new InSideClass();
    

    If InsideClass was public and I wanted to instantiate InSideClass from a function that is not a member of OutSideClass, I'd type:

    OutSideClass::InSideClass *instance = new OutSideClass::InSideClass();
    

    InSideClass and OutSideClass are otherwise entirely separate, unlike in other languages like Java.

    0 讨论(0)
  • 2020-12-05 10:36

    There are no special access priveleges for the nested class to an enclosing class.

    0 讨论(0)
  • 2020-12-05 10:48

    Question 1> Is it true that OutSideClass can ONLY access public members of InSideClass

    Yes

    Question 2> Is it true that InSideClass can access all members of OutSideClass

    No, in C++03. Yes, in C++11.


    The Standard text is very clear about this:

    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.

    However, the Standard quotation has one defect. It says the nested classes don't have access to private members of the enclosing class. But in C++11, it has been corrected: in C++11, nested classes do have access to private members of the enclosing class (though the enclosing class still doesn't have access to private members of the nested classes).

    See this Defect Report :

    • 45. Access to nested classes
    0 讨论(0)
提交回复
热议问题