Scoping and Friends in Nested Classes

Summary

In this post, I will introduce the scoping in nested classes and how friend classes work here.

Conclusion

The rules are,

  1. As any member of its outer class, nested classes have access to all names (private, protected, etc) to which the outer class has access; however, outer classes have no special access to inner classes' members;
  2. Declarations in a nested class can use any members of the enclosing class, following the usual usage rules for the non-static members;
  3. B wants to use the private functions in A. Declare the friend class B in A, which means B is a friend of A.
class PrivateClass;

class Outer {
private:
    static void PrivateFunction() {}

public:
    class Inner {
        // outer classes do not have special access to private members of inner classes
        //  to call Inner::PrivateFunction(), Outer must be a friend of Inner
        friend class Outer;
    public:
        Inner();

    private:
        static void PrivateFunction() {}
    };
public:
    void PublicFunction() {
        // outer classes do not have special access to private members of inner classes
        Inner::PrivateFunction();
    }
};

class PrivateClass {
    // nested classes can be a friend of other normal classes
    friend class Outer::Inner;
private:
    explicit PrivateClass(int a) {}
};

Outer::Inner::Inner() {
    PrivateClass instance(1);
    // nested classes can access private members of outer classes
    PrivateFunction(); 
}

Leave a Reply

Your email address will not be published. Required fields are marked *