Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ nested classes accessibility

Tags:

c++

oop

Given the following code without considering friendship between two classes:

class OutSideClass { ... public:     int i_pub; protected:     int i_pro; private:     int i_pri;      class InSideClass     {         ...         public:             int j_pub;         protected:             int j_pro;         private:             int j_pri;     }; }; 

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

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

Please correct me if my understanding is not correct.

like image 380
q0987 Avatar asked Aug 09 '11 15:08

q0987


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.

What is a nested class how can we access members of a nested class?

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.

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.

How do you access class within a class?

They are accessed using the enclosing class name. To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass.


1 Answers

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
like image 167
Nawaz Avatar answered Sep 27 '22 22:09

Nawaz