Question

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?

Was it helpful?

Solution

look at this link

A friend function is a function that is not a member of a class but has access to the class's private and protected members. Friend functions are not considered class members; they are normal external functions that are given special access privileges. Friends are not in the class's scope, and they are not called using the member-selection operators (. and –>) unless they are members of another class. A friend function is declared by the class that is granting access. The friend declaration can be placed anywhere in the class declaration. It is not affected by the access control keywords.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top