Reputation: 237
Is it necessary to write an object in friend function to access private members of the class.
#include <iostream>
#include <vector>
using namespace std;
class project
{
private:
vector<int> v1;
public:
void addelement(int a)
{
v1.push_back(a);
}
void view()
{
for(auto i=v1.begin();i<v1.end();i++)
{
cout<<*i<<endl;
}
}
friend void modify(int,int,project);
};
void modify(int data,int index,project p)//is it necessary here to make an object of class .
{
p.v1[index]=data;//As here without "p." it shows errors,it says use
//of unidentified identifier v1
}
int main()
{
project p1;
p1.addelement(7);
p1.addelement(91);
modify(24,0,p1);
modify(22,3,p1);
p1.view();
}
I wonder if a friend function is a friend of a class and it can access private members of class on its own then why there is need to mention object of that class?
Upvotes: 0
Views: 67
Reputation: 238391
Only non-static member functions are called on an object like this:
object_arg.name_of_member_function(regular_args);
And as such, non-static member functions have access to the this
pointer that points to the object_arg
, and implicitly the members of the object pointed by this
.
All other functions, which consist of static member functions and free functions, including those free functions that are friends of a class such as your modify
, are called without an object argument like this:
name_of_function(regular_args);
As such, they have no this
pointer. If you want to access some object, you have to pass it as a regular argument.
P.S. Modifying an argument that was passed by value is mostly useless.
Upvotes: 4
Reputation: 40862
A friend
function is not a member function of that class.
How should modify(24,0)
know to which instance of project
you are referring to? As of that, you need to pass the instance of project
to that friend
function.
An additional note, void modify(int data, int index, project p)
creates a copy of p
, if you want to modify the object you pass to modify
you need to either write:
void modify(int data, int index, project &p) {
p.v1[index]=data;
}
//...
modify(24,0,p1)
or
void modify(int data, int index, project *p) {
p->v1[index]=data;
}
//...
modify(24,0,&p1)
Upvotes: 4