-1

I tried to realize the friend class to provide the members's value for the member of another class.

I' ve tried to make the object of class Friend and defined it as Attempt's argument and after replace &Friend::fri to object.fri() but it was not compiled also.

 class Friend {
  public:
    int val = 0;
int fri() {
    val = 456;
    return val;         
          }
friend class Partner;
 };

 class Partner {    
  public:
//(corrected) Friend Object;
int Attempt() {
    std::cout << "The value from the friend class: " << 
     &Friend::fri /*(corrected) Object.fri()*/<<"\n"; // '&' was requred by compiler to make pointer to 
                        //the member
    return 0;
      }
 };

I expected Attempt to write the value from fri(). But there's 1 and I can't undertand where is this 1 from.

Konstantin
  • 111
  • 1
  • 8

1 Answers1

0

The friend keyword simply lets non-member functions have access to private/protected members of another class. Unless your method is static, or inheritance is involved, you're still going to need an object to call that method. Take for example:

Friend f;
int Attempt(){
    std::cout << "The value from the friend class: " << f.fri();
}

This will produce the output you're expected.

BTables
  • 4,413
  • 2
  • 11
  • 30
  • Thanks, indeed it returned required value. – Konstantin Sep 17 '19 at 17:19
  • @Konstantin Glad it helped. Feel free to mark it as correct if it solved your problem in case someone else runs across this problem in the future :) – BTables Sep 17 '19 at 17:34
  • previous time I corrected code and after somebody wrote not to do this, now I really don’t know what to do after the problem’s been solved) Guess if I make remarks in the code it’ll be the best solution) – Konstantin Sep 17 '19 at 17:59