tags:

views:

247

answers:

3

I know it's possible to create a friend function in C++:

class box
{
friend void add(int num);
private:
int contents;
};

void add(int num)
{
box::contents = num;
return;
}

But is there a way to create friend classes?

NB: I know there are probably a lot of errors in this code, I don't use friend functions and am still pretty new to the language; if there are any, please tell me.

+6  A: 

Yup - inside the declaration of class Box, do

friend class SomeOtherClass;

All member functions of SomeOtherClass will be able to access the contents member (and any other private members) of any Box.

Charlie Tangora
And I assume that to define the SomeOtherClass, you just write "SomeOtherClass{public: int someothercontents;};" outside of the Box declaration?
Keand64
@Keand64: SomeOtherClass will be a properly defined class, so yes, you do whatever you did to define class Box.
Dunya Degirmenci
+2  A: 

By the way, a design guideline is that, if a class is close enough to be declared a friend, then it's close enough to be declared as a nested class in the same header file, for example:

class Box
{
  class SomeOtherClass
  {
    //some implementation that might want to access private members of box
  };
  friend class SomeOtherClass;
private:
  int contents;
};

If you don't want to declare the other class as a nested class in the same header file, then perhaps you shouldn't (although you are able to) declare it a friend.

ChrisW
A: 

In your code, you are currently using the box member 'contents' as a static member in the add function ( box::contents = num; )

You should either declare contents as being static, like so: (you also have to initialize it then..)

class box
{
    friend void add(int num);
    private:
      static int contents;
};

int box::contents;

void add(int num)
{
    box::contents = num;
    return;
}

or, change your add function to accept a box object and an int:

class box
{
    friend void add(box *b, int num);
    private:
      int contents;
};

void add(box *b, int num)
{
    b->contents = num;
    return;
}
DeadHead