14

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?

anastaciu
  • 23,467
  • 7
  • 28
  • 53
Neo
  • 1,031
  • 2
  • 11
  • 27

1 Answers1

31

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53