sparsh goyal
sparsh goyal

Reputation: 131

Friend Function definition inside class

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()

Upvotes: 0

Views: 73

Answers (1)

Ian
Ian

Reputation: 172

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.

Upvotes: 1

Related Questions