Emerald Weapon
Emerald Weapon

Reputation: 2540

Friend function in-class definition only allowed in non-local class definitions. What does it mean?

Here (see point 2 description) I read that a friend function in-class definition is only allowed in non-local class definition.

What does that mean?

Upvotes: 3

Views: 373

Answers (3)

Patryk
Patryk

Reputation: 24120

A non-local class definition is a definition that is not defined in other class' body or it not embedded in a function body.

So basically you can do this:

#include <iostream>

struct NonLocal
{
  friend std::ostream& operator<<(std::ostream& os, const NonLocal& l)
  {
    os << l.x;
    return os;
  }

private:
  int x;
};

int main()
{
  NonLocal nl;
  std::cout << nl;
}

but you cannot do this:

#include <iostream>

int main()
{
  struct Local
  {
    friend std::ostream& operator<<(std::ostream& os, const Local& l) // this will fail to compile
    {
      os << l.x;
      return os;
    }

  private:
    int x;
  };

  Local l;
  std::cout << l;
}

From the cppreference.com:

A class declaration can appear in namespace scope (in which case it defines an ordinary class), inside another class definition (in which case it defines a nested class), and inside the body of a function, in which case it defines a local class. The name of such a class only exists within the function scope, and is not accessible outside.

  • A local class cannot have static members
  • Member functions of a local class have no linkage
  • Member functions of a local class have to be defined entirely inside the class body
  • Local classes other than closure types (since C++14) cannot have member templates
  • Local classes cannot have friend templates
  • A local class inside a function (including member function) can access the same names that the enclosing function can access.
  • local classes could not be used as template arguments (until C++11)

[emphasis mine]

Upvotes: 3

Mattia F.
Mattia F.

Reputation: 1740

It means that you cannot do this:

void function ()
{
    class X
    {
        int a;
        friend void friend_set(X& p, int i)
        {
            p.a = i;
        }
        public:
        void member_set(int i)
        {
            a = i;
        }
    };
}

Local-classes are the ones defined inside a function.

Upvotes: 2

milleniumbug
milleniumbug

Reputation: 15814

Non-local class is a class that's not local.

A local class is a class defined in a function - see paragraph "Local classes" on this page

"Friend function in-class definition" refers to ability to declare and define a non-member function inside a class, which is a friend of the class it's enclosed in.

class a_class
{
    friend std::ostream& operator<<(std::ostream& os, const a_class& x)
    {
        // ...
    }
};

Upvotes: 3

Related Questions