Hi friends,
I was understanding the concept of friend functions. I read in my book that there are two possible ways of "making friendship":cool:
1. Make a class a friend.
2. Make the method in a class a friend.
I am able to write a code for the first point. But when I tried the second one, I got the error as said in the title.
Here is my piece of code. To make this less lengthier I have put .h and .cpp file in one code block.
/****************** MyClass.h ***************/
#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass
{
public:
MyClass();
int GetprivVar1() { return privVar1; }
//friend class FriendClass;
friend void FriendClass::changeMyVariable(MyClass*);
protected:
private:
int privVar1;
};
#endif // MYCLASS_H
/****************** MyClass.cpp ***************/
#include "../include/MyClass.h"
MyClass::MyClass()
{
privVar1 = 0;
}
/****************** FriendClass.h ***************/
#ifndef FRIENDCLASS_H
#define FRIENDCLASS_H
#include "MyClass.h"
class FriendClass
{
public:
FriendClass();
void changeMyVariable (MyClass *);
protected:
private:
};
#endif // FRIENDCLASS_H
/****************** FriendClass.cpp ***************/
#include "../include/FriendClass.h"
FriendClass::FriendClass()
{
//ctor
}
void FriendClass::changeMyVariable(MyClass* obj)
{
obj->privVar1 = 9;
}
#include <iostream>
#include "include/FriendClass.h"
#include "include/MyClass.h"
using namespace std;
int main()
{
MyClass obj1;
FriendClass obj2;
cout<<"before : "<<obj1.GetprivVar1();
obj2.changeMyVariable(&obj1);
cout<<"after : "<<obj1.GetprivVar1();
return 0;
}
Here I'm talking about lines 12 and 13 in first code block (MyClass.h).
If I make a class a friend it works, but making friendship with the function is giving compiler error
error: 'FriendClass' has not been declared