Reputation: 3112
I've been trying to write up a code to implement a member function that could access private data of a class by declaring it as a friend within the class. But my code is failing and I can't seem to figure out what's wrong with it:
#include <iostream>
using namespace std;
class A;
class B
{
private:
int b; // This is to be accessed by member function of A
public:
friend void A::accessB();
};
class A
{
private:
int a;
public:
void accessB();
};
void A::accessB()
{
B y;
y.b = 100;
cout << "Done" << endl;
}
int main(void)
{
A x;
x.accessB();
}
I am trying to access the private contents of B making use of getAccessB function which is member function of A. I have declared it as a friend. What's wrong with this?
Upvotes: 4
Views: 96
Reputation: 29966
The ordering. If you are referring to A::accessB
, A
must be declared by that point. Place the A
class above the B
, and it will work fine.
Upvotes: 1
Reputation: 65620
A::accessB
is not declared at the point of the friend
declaration, so you can't refer to it. You can fix this by shifting the order of definitions and declarations such that A::accessB
is visible to B
:
class A
{
private:
int a;
public:
void accessB();
};
class B
{
private:
int b;
public:
friend void A::accessB();
};
void A::accessB()
{
B y;
y.b = 100;
cout << "Done" << endl;
}
Note that making a function a friend
just so that it can modify your private state is a bad code smell. Hopefully you are just doing this to understand the concepts.
Upvotes: 3