c++inner-classesaccess-modifierspublic-members

Can't use public nested class as private method parameter


In the following code:

class Outer {
   private:
    void f_private(Outer::Inner in); // Wrong

   public:
    class Inner {};
    void f_public(Outer::Inner in); // OK
};

f_private() cannot use nested class Outer::Inner as parameter type. But it's ok to do so in f_public().

Can someone explain to me in what rule this is based on, and what's the benefit it?


Solution

  • The problem is not that it's public or private, it's the order. This may seem strange, with other class members this is not a problem, but consider that in this case you are declaring a new user defined type, because of that you must declare it before you use it:

    class Outer 
    {
    public:
        class Inner {};   
        void f_public(Outer::Inner in);  // OK
    
    private:
        void f_private(Outer::Inner in); // OK
    };
    

    Or:

    class Outer
    {
    public:
        class Inner;                          // declare
        void f_public(Outer::Inner in);       // OK
    
    private:
        void f_private(Outer::Inner in);       // OK
    };
    
    class Outer::Inner {};                     // define
    
    void Outer::f_private(Outer::Inner in){}   // method definition after class definition
    
    void Outer::f_public(Outer::Inner in){}    //
    

    If you use the class as pointer or reference parameter then there is no need to define it before, a forward declaration will be enough.