I have the following code:
Master.h
#ifndef MASTER_H
#define MASTER_H
class Master
{
friend class Friend;
public:
Master(void);
~Master(void);
void CallFriendFunction(int largeData);
private:
int largeData;
//Want this class to share largeData;
Friend testFriend;
};
#endif // MASTER_H
Master.cpp
#include "Master.h"
Master::Master(void)
{
//Inentionally left blank
}
Master::~Master(void)
{
//Intentionally left blank
}
void Master::CallFriendFunction(int largeData)
{
this->largeData = largeData;
this->testFriend.Test(this);
}
Friend.h
#ifndef FRIEND_H
#define FRIEND_H
#include "Master.h"
class Friend
{
public:
Friend(void);
~Friend(void);
void Test(Master* masterPtr);
};
#endif // FRIEND_H
Friend.cpp
#include "Friend.h"
#include <iostream>
Friend::Friend(void)
{
//Intentionally left blank
}
Friend::~Friend(void)
{
//Intentionally left blank
}
void Friend::Test(Master* masterPtr)
{
std::cout << masterPtr->largeData << std::endl;
}
I want class Friend to be able to share Master’s private members. However, I can’t get this code to compile. I’ve tried Forward Declaration, and #includes, but I start getting into circular dependencies. When Friend class is not a member of Master class, the code compiles?
Is it possible for Friend class be a member of Master and be friends?
How else can Friend class have access to Masters private members?
You need the following includes and forward declarations:
In Master.h:
In Friend.h:
In Friend.cpp:
Putting the forward declaration in
Friend.hprevents circular dependency. A forward declaration is enough there because you only declare aMaster*parameter, without using its members yet.You do need to include
Friend.hfromMaster.hbecause you are declaring aFriendmember, and this requires a complete type.