TransWikia.com

friend class and the scope of function arguments

Stack Overflow Asked by user2269707 on December 25, 2021

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 Answers

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

Answered by lubgr on December 25, 2021

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) {}

Answered by songyuanyao on December 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP