Your understanding regarding friend
function is wrong. If you declare a function friend
to another class, it means the friend
function can access private members of that class, it does not mean the friend
function becomes a class member.
Here doStaff()
is friend
to B
, not a member of B
. But you are using it on an object of B
, hence compiler saying that it is not member of that class. using friend
gives doStaff
permission to access B
's private
members in it.
The tutorial you are following says it clearly. duplicate()
method is a friend to Rectangle
, hence it can access the private
members width
and height
, but duplicate()
is not used as a class method of Rectangle
.
In summary, your question is wrong. You can access a friend
function just like any free (non-class method) function. The question is how friend
functions accesses the member of a class to which it is friend, and as said, it can access everything in that class, which is the motivation of having friend functions, namely to give access of private members of a class to a outsider.
Similarly a friend
class can access everything of the class to which it is friend.
So for your problem, either you remove friend
from doStaff
to make it a member of B
. But I guess your intention was to use friend
method, in that case you can do the following:
void doStuff(B b, int i)
{
b.m_stuff = i; // it is friend function of B, so can access m_staff
}
or you can make doStaff()
member of A
and then you can write
class A{
//other members
void doStaff(B& b, int i){ b.m_staff=i;}
void A::testStuff() {
B b {B()};
doStuff(b,1); //although u can just write "b.m_staff = 1;" right here
}