Sachin Bhikule Sachin Bhikule - 3 months ago 16
C++ Question

how to make two classes friend of each other?

#include <iostream>
using namespace std;
class hello;
class demo
{
private :
void fun()
{
printf ("Inside fun \n");
}
public :
void sun()
{
hello hobj;
hobj.run();
}
friend class hello;
};

class hello
{
private :
void run ()
{
printf("Inside Run \n");
}
public :
void gun ()
{
demo dobj;
dobj.fun();
}
friend class demo;
};

int main ()
{
demo dobj1;
dobj1.sun();
cout<<"Inside Demo \n";
hello hobj1;
hobj1.gun();
cout<<"Inside hello \n";
return 0;
}


How to make two classes friends of each other ?
i know how to make one class friend of other class but don't know how to make it friend of each other ,i tried separate forward declaration for both the classes still not working ? is it possible to do this ?

it keeps giving me these errors

error C2228: left of '.run' must have class/struct/union
error C2079: 'hobj' uses undefined class 'hello'

Answer

I think your problem is in the usage of incomplete type here:

void sun() {
  hello hobj;
  hobj.run();
}

When you're defining the function sun() the class hello has been declared but not defined yet. That's why you cannot use it in a function, and the compiler should give you an error.

In order to solve that problem just define the function sun() later, after the definition of hello class.

So your class demo will be:

class hello;

class demo {
 // ...
 public:
  void sun();  // declaration  
  friend class hello;
};

// ...

class hello {
 // ...
};

void demo::sun() {
  // here the implementation and you can use 'hello' instance w/o problem.
  hello hobj;
  hobj.run();
}
Comments