Hi ,

I am just curious to know that , why i am not able to compile below code if i define access function inside the class.

i am able to execute another friend function inside the class. Does it mean class scope is responsible for the execution of other friend function or due to having global scope it execute code oustside class.

#include<iostream>
#include<memory>
#include<process.h>
using namespace std;

class a
{
int i;
public:
    void display ()
    {

    cout<<"Hello";

    }
/*friend void access();*/
    friend void access()
    {   a x;
        x.i=10;
        cout<<x.i;

    }

   /* friend void access(a & x)  works fine if object passed explicitly
        {
            x.i=10;
            cout<<x.i;

        }*/



    friend a operator --(a &x)
    {
    x.i=x.i-1;
    return x;
    }


};

/*void access()  it works fine
{
a obj;
obj.i=10;
cout<<obj.i;
}*/
int main()
{
a obj;
--obj;
access();//Error:Access was not declared in this scope

//access(obj)
return 1;

}

The C++ standard says this at section 11.3/7:

Such a function is implicitly inline. A friend function defined in a class is in the (lexical) scope of the class in which it is defined. A friend function defined outside the class is not (3.4.1).

This means that you can call "access()" from within the class (e.g., in the function body of a member function of the class), but the function is not visible (lexical scope) from the outside.

To solve the problem, you have to, at least, declare the function outside the class. For example, like this:

#include <iostream>
#include <memory>

using namespace std;

void access();

class a
{
    int i;
public:
    void display ()
    {
      cout<<"Hello";
    }

    friend void access()
    {
      a x;
      x.i = 10;
      cout << x.i;
    }

    friend a operator --(a &x)
    {
      x.i = x.i-1;
      return x;
    }

};

int main()
{
  a obj;
  --obj;
  access();
  return 1;
}
This question has already been answered. Start a new discussion instead.