I am learning C++, and I’m trying to learn more about using the friend keyboard.
However, I am having trouble using nested classes in my Header file.
I know that header files should only be used for declarations but I didnt want to include a cpp file with it so I just used a header file to declare and build.
Anways, I have a main.cpp file that I want strictly to be used for creating objects of classes and accessing its functions.
However, I dont know exactly how to create the FriendFunctionTest function in my header file to where I can access it in my main.cpp source file using the header Class object because I’m trying to understand the “friend” keyword.
Here is my header code:
#ifndef FRIENDKEYWORD_H_
#define FRIENDKEYWORD_H_
using namespace std;
class FriendKeyword
{
public:
FriendKeyword()
{//default constructor setting private variable to 0
friendVar = 0;
}
private:
int friendVar;
//keyword "friend" will allow function to access private members
//of FriendKeyword class
//Also using & in front of object to "reference" the object, if
//using the object itself, a copy of the object will be created
//instead of a "reference" to the object, i.e. the object itself
friend void FriendFunctionTest(FriendKeyword &friendObj);
};
void FriendFunctionTest(FriendKeyword &friendObj)
{//accessing the private member in the FriendKeyword class
friendObj.friendVar = 17;
cout << friendObj.friendVar << endl;
}
#endif /* FRIENDKEYWORD_H_ */
In my main.cpp file, I wanted to do something like this:
FriendKeyword keyObj1;
FriendKeyword keyObj2;
keyObj1.FriendFunctionTest(keyObj2);
But obviously its not going to work since the main.cpp cant find the FriendFunctionTest function in the header file.
How do I fix this issue?
And I apologize again, I’m just trying to learn C++ online.
The
friendkeyword is only used to specify if a function or other class can have access to the private members of that class. You have no need for class inheritance or nesting becauseFriendFunctionTestis a global function. Global functions do not require any class prefixes when invoked.Source for
friend: http://msdn.microsoft.com/en-us/library/465sdshe(v=vs.80).aspx