On Jan 7, 10:09 pm, Rahul <sam_...@yahoo.co.inwrote:
Hi Everyone,
The following code works fine,
class A
{
private: friend void sample(A& obj)
{
printf("in friend...\n");
printf("%d",obj.i);
}
public: A()
{
this->i = 5;
}
private: int i;
};
int main()
{
A obj;
sample(obj);
return(0);
}
I'm wondering what could be the significance of the private access
specifier to the friend function, what difference does it make?
Thanks in advance!!!
friend functions, like sample(A& obj) are more like gang members. They
respect no rules, access specifiers don't apply.
Specifically, someone could change sample(A& obj) and modify the
internal parts of your objects.
Some friends make sense (like usefull operators that need access to
your private parts).
These don't violate your encapsulation since the instance of your
class is passed as a reference_to_const.
(note: const A& below)
#include <iostream>
#include <ostream>
class A
{
int i;
public:
A() : i(5) { }
// friend op
friend std::ostream&
operator<<(std::ostream&, const A&);
};
std::ostream&
operator<<(std::ostream& os, const A& a)
{
os << "i = " << a.i;
return os << std::endl;
}
int main()
{
A obj;
A another;
std::cout << obj << another << std::endl;
}
/*
i = 5
i = 5
*/