friend class and the scope of function arguments

70 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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};
}
0
On

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

It depends on whether A::i is accessible at the caller side; because &A::i is passed as the argument at the caller side.

For example, Field is friend of A, then A::i is accessible in Field. e.g.

Field() : p(&A::i) {}