0

When I try to implement friend function inside the class as shown below, I get an error, and I don't know why... It only happens when a non-argumental friend function is declared inside the class. The error is

display() is not defined in this scope

Code:

#include<iostream>
using namespace std;

class test{

    private: 
    int x = 5;


    public:

    friend void display(){
        test obj;
        cout << obj.x << endl;

    }
};


int main(){


    display();

    return 0;
}

Output should be simply: 5

But I get this error:

display is not defined()

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sparsh goyal
  • 89
  • 1
  • 7
  • https://stackoverflow.com/questions/8207633/whats-the-scope-of-inline-friend-functions – Mat Jun 11 '19 at 15:40
  • but it is declared as friend ...so no class instance is required.... – sparsh goyal Jun 11 '19 at 15:41
  • 1
    Possible duplicate of [What's the scope of inline friend functions?](https://stackoverflow.com/questions/8207633/whats-the-scope-of-inline-friend-functions) – DSC Jun 11 '19 at 15:42
  • friend functions are not instance functions but still can access private members; that's why they are special functions. Think it this way, if you will declare the function inside the class as an instance method, you are already getting to access the private members, then why you need to make it friend – Sisir Jun 12 '19 at 18:06
  • Rule of thumb, friend functions are always non-instance functions. – Sisir Jun 12 '19 at 18:07

1 Answers1

1

I'm not sure why you need to do this, but if you have to, define the display() method outside the class.

class Test
{  
   private: 
      int x = 5;

   public:    
      friend void display();
};

void display()
{
    Test obj;
    cout << obj.x << endl;
}

int main()
{   
    display();    
    return 0;
}

Though in general, I try to avoid friend classes/functions. I don't know exactly what you're trying to accomplish, but I'd rethink your approach.

Ian
  • 172
  • 9