Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ nested classes - inner/outer relationship

Tags:

c++

I read some posts about Nested Classes in our community and outside and I'm pretty confused.

As far as I understand, in C++, Nested Classes aren't not any different from separate/independent classes.

While I was trying to understand the conecpt better I wrote a simple code and I found out that an inner class can access an outer class without being given friendship from the outer class.

For example:

class Outer {
private : // default access modifier
    int x;
    static int sx;
public:
    class Inner {
    public:
        void changeOuterDataMemberValues(int value) {
            sx = value; // changes the private static data member of Outer.

            Outer out;
            out.x = value; // changes the private data member via object (not via class!)
        }
        void printMyOuterDataMember()  {
            cout << sx; // prints the private data member of Outer.
        }
    };
};


class Lonesome {
    void tryingToChangeDataMemberValue(int value) {
        Outer::sx = value; // cannot change the private static data member of Outer.
    }
};

int Outer::sx;

You can see that the Inner class which is nested in the Outer class has access to its(the Outer class) data members whilst the Lonesome as independent class cannot access the Outer class data member.

I apologize if this is a duplicate or stupid question, but I just want to confirm with you guys that there is a difference between a Nested Class and independent class (two different classes which don't have inner / outer relationship).

Thank you all, Syndicator =]

like image 493
SyndicatorBBB Avatar asked Jan 30 '13 15:01

SyndicatorBBB


1 Answers

There is a difference between C++03 and C++11 in this regards. So the answer varies depending on which compiler you are using.

If you are using a C++03 compliant compiler then:

Nested class cannot access all members of the enclosing class.

If you are using C++11 compliant compiler then:

Nested class can access all members of the enclosing class. Nested class is treated as just another member of the class.

C++03 Standard 11.8 Nested classes:
§1

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 shall be obeyed.

C++11 Standard 11.7 Nested Classes:

A nested class is a member and as such has the same access rights as any other member.

like image 70
Alok Save Avatar answered Sep 27 '22 16:09

Alok Save