0

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'
2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by zawpai
0

>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.

0

Hi John A,

You are right. I should do a forward declaration.

Thanks,
zawpai

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.