Search code examples
c++access-specifier

What purpose do access specifiers for nested class serve?


Suppose I have a class A with a private nested class B. As I understand it, that means B is not part of the public API. Does that mean that the public and private access specifiers only server the programmer rather than the user? Are there ways that I might accidentally give the user access to public data members of a private nested class?


Solution

  • Having a private nested class does not mean that you can't accidentally make it available to the "user":

    #include <iostream>
    #include <type_traits>
    
    class A {
    
    private:
      class B {
      public:
        int x = 2;
      };
    
    public:
      B getB() { return B(); }
    };
    
    int main() {
      A a;
      
      // a returns B so you have access to the public member x
      auto b1 = a.getB();
      std::cout << b1.x << std::endl;
        
      // or get the return type to create an instance of B  
      using B = std::result_of_t<decltype(&A::getB)(A)>;
      B b2;
      std::cout << b2.x << std::endl;
    }
    

    So if you have a function in A that is public, and exposes B (or any other function that is able to expose B and to which the "user" as access to) then the user will be able to refer to that nested class even if it is private.

    protected and private prevent you from refering to the names directly, but if you purposely (or accidentally) expose them in a different way, then this access modifier won't protect you from that.