Hi , xd i wasn't able to respond , i was away but my friends did to add on what they said , i will give you some simple illustration;
. classes and structs
- one of the reasons we use these constructs is to group data together.
- classes do have data members{variables} and procedures for manipulating data
stored within the classes
2. friendship
- according to the natural rules of encapsulation in c++ a class best enforces data encapsulation by keeping all data members private and only allowing access to them via procedures { functions}.
** when it comes to friendship , we want to violate this encapsulation rule for access advantage to the class data, here we allow other classes and procedure to directly access the class *data* without using procedures{getters&setters} but all other class properties remain the same;
a. data initialization, manipulation etc. aren't affected by friendship, only the means of
access is.
here is an example similar to what my friends gave:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
class foo
{
private:
int value;
string name;
public:
friend ostream& operator<<(ostream& os, const foo& obj);//this operator is reasonably
// friend to minimize operations required.
foo(int val,string s):value(val),name(s){}
};
ostream& operator<<(ostream& os,foo& obj)
{
os<<obj.value<<" "<<obj.name<<endl;//direct access to members is legal here
return os;
}
///compare to what could be done without using friendship
class bar
{
private:
int value;
string name;
public:
int get_value() const;///we would have to use getters
string get_name() const;// hence above we used friendship to cut this access cost
//but that blows a hole into data encapsulation.
};
ostream& operator<<(ostream& os,const bar& obj);//not a friend hence declared outside the class
int bar::get_value() const{return value;}
string bar::get_name() const{ return name;}/// this is the legal access means when encapsulation is maintained.
ostream& operator<<(ostream& os,const bar& obj)
{
///os<<obj.value<<" "<<obj.name<<endl; this access method would be illegal here
/// because all members are private.
os<<obj.get_value()<<" "obj.get_name()<<endl;///this is what encapsulation allows at
//best and above we did circumvent that by making operator<< a friend to the class foo.
return os;
}
/// both classes have overloaded versions of << operator which basically achieves the same thing but uses different access modes to class data members.
|
Well that's what friendship entails.
i hope that would help too.