8

Is this legal? If not, will the following code allow this?

class Foo
{
    friend class Foo;
}
Xirdus
  • 2,997
  • 6
  • 28
  • 36

4 Answers4

24

That's redundant. Foo already has access to all Foo members. Two Foo objects can access each other's members.

class Foo {
public:
  int touchOtherParts(const Foo &foo) {return foo.privateparts;}
private:
  int privateparts;
};

Foo a,b;
b.touchOtherParts(a);

The above code will work just fine. B will access a's private data member.

JoshD
  • 12,490
  • 3
  • 42
  • 53
  • 3
    @Alex: it's an old C++ pun, that C++ is probably the only language where one allow one's friends to touch one's private parts :) – Matthieu M. Sep 30 '10 at 18:40
5

Yes it is legal for an object of class Foo to access the private members of another object of class Foo. This is frequently necessary for things like copy construction and assignment, and no special friend declaration is required.

Tyler McHenry
  • 74,820
  • 18
  • 121
  • 166
3

It is redundant and unnecessary. Moreover, I get the following warning in g++

warning: class ‘Foo’ is implicitly friends with itself
Arun
  • 19,750
  • 10
  • 51
  • 60
2

Classes friending themselves makes sense if they're templates, as each instantiation with distinct parameters is a different class.

LogicBreaker
  • 105
  • 6