Search code examples
c++friend-class

friend class and the scope of function arguments


I'm writing a reflection utility for self usage, I simplified the code(remove complicated templates) as below:

class A {
 private:
  friend class Field;
  int i;
};

class Field {
 public:
  Field(int A::* p) : p(p) {}
 private:
  int A::* p;
};


Field field(&A::i);

the compiler complains about i is private of class A.

I'm confused now, I know that parameters have a scope of function prototype scope, but I don't know much about it's relationship with the C++ feature friend classes.

Can anyone help what should I do to pass the private &A::i to the field object?


Solution

  • In the line

    Field field(&A::i);
    

    you are accessing a private data member pointer (&A::i) from within a toplevel scope. This is not related to the class Field being a friend of A. What you could do instead, is giving friend access to a function that is supposed to instantiate Field objects, e.g.

    class Field;
    
    class A {
     private:
      friend Field createField();
      int i;
    };
    

    The definition of Field itself can remain unchanged, while the builder function could be

    Field createField()
    {
        // Works: &A::i is a private member, but createField is a friend
        return Field{&A::i};
    }