I'm a newbie to C++.I wrote a simple program to implement the use of friend functions. The code is as follows:-
#include<iostream>
using namespace std;
class one
{
private:
int age;
public:
one()
{
age=1;
}
void setData(int num)
{
age=num;
}
friend int returnOne()
{
return age;
}
};
class two
{
private:
int roll;
public:
two()
{
roll=0;
}
void setData(int num)
{
roll=num;
}
friend int returnTwo()
{
return roll;
}
};
int main()
{
one a;
two b;
cout<<a.returnOne()<<endl<<b.returnTwo()<<endl;
}
I'm getting the following error in c++.
friend.cpp: In function ‘int returnOne()’:
friend.cpp:8:6: error: invalid use of non-static data member ‘one::age’
friend.cpp:20:9: error: from this location
friend.cpp: In function ‘int returnTwo()’:
friend.cpp:27:6: error: invalid use of non-static data member ‘two::roll’
friend.cpp:39:9: error: from this location
friend.cpp: In function ‘int main()’:
friend.cpp:47:10: error: ‘class one’ has no member named ‘returnOne’
friend.cpp:47:31: error: ‘class two’ has no member named ‘returnTwo’
EDIT Thanks.It solved the problem.
But it now leads me to another question.Isn't the friend keyword now compromised the purpose of using private
,as now any class or function can simply use the friend function to access private data members.If yes,them we could have simply declared the data member as public
instead of private
.Whats so special in using private
?
look at this link