Is it possible to create a "friend class" in C ++?

I know it is 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 bugs in this code, I am not using friends functions and still quite new to the language; if they are, please tell me.

+1


a source to share


3 answers


Yup - inside the declaration class Box

, do

friend class SomeOtherClass;

      



All member functions SomeOtherClass

will be able to access the item contents

(and any other private members) of anyone Box

.

+7


a source


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

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 another class as a nested class in the same header file, then perhaps you should not (although you can) declare it as a friend.

+2


a source


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

You must either declare the content as static, eg: (you must initialize it too ..)

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

int box::contents;

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

      

or, change the add function to accept a box 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;
}

      

0


a source







All Articles