Hi,

Why I get the errors when using 'friend function'?

// friend function as bridges on two different objects

#include <iostream>
using namespace std;

class alpha
{
private:
	int data;
public:
	alpha() { data = 3; }
	friend int frifunc(alpha, beta);	// friend function
};

class beta
{
private:
	int data;
public:
	beta() { data = 7; }
	friend int frifunc(alpha, beta);	// friend function
};

int frifunc(alpha a, beta b)			// friend function definition
{
	return (a.data + b.data);
}

int main()
{
	alpha aa;
	beta bb;

	cout << frifunc(aa,bb);

	return 0;
}

When I compile it, the system show me this two errors.

error C2061: syntax error : identifier 'beta'
error C2248: 'data' : cannot access private member declared in class 'alpha'

>When I compile it, the system show me this two errors.
The first error is because the compiler has no idea what 'beta' is. Look at this section of code:

class alpha
{
private:
	int data;
public:
	alpha() { data = 3; }
	friend int frifunc(alpha, beta);	// friend function
};

Up until this point, 'beta' has never been declared. This is a circular dependency problem because both classes must make references to each other, but both must be declared before they can be referenced. The solution is to use a forward declaration: declare the class, but don't give the full definition of it. It works like this:

class myClass; // << this is a forward declaration

class otherClass
{
  myClass *myObject; // now we can use myClass
};

class myClass
{
  otherClass *myObject; // we can also use otherClass
};

I'll let you take it from there.

Hi John A,

You are right. I should do a forward declaration.

Thanks,
zawpai

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.