Friend function part 1 | very very easy
Friend function:
- Friend function is not a member function of a class to which it is a friend.
- Friend function is declared inside the class with friend keyword.
- It must be defined outside the class to which it is friend.
- Friend function can access any member of the class to which it is a friend.
- Friend function can not access the members of the class directly.
- Friend function can not access members of the class directly because it has no caller object.
- It should not be defined with membership label.
Let's consider a simple example to implement all above points:
#include<iostream>
using namespace std;
class Complex{
private:
int a, b;
public:
void setData(int x, int y){
a=x;
b=y;
}
void showData(){
cout<<a<<" "<<b<<endl;
}
friend void add( Complex ); // 2. friend function declared inside the class
};
//1. and 7. As friend function is not a member function so it is not defined using member ship label or scope resolution operator.
void add( Complex c ){ // 3. friend function defined outside the class
cout<<"Sum is:"<<endl<<c.a+c.b<<endl;
}
int main(){
// creating object of class Complex
Complex c1;
c1.setData( 42, 87 ); // here c1 is the caller object
//4. 5. 6. as our friend function does not have a caller object it is called directly
add(c1); // but to access the members of the class we have to pass the object to the
// friend function so the compiler can determine whose members to be used.
return 0;
}
Output:
Sum is:
129
Friend function as friend of more than one classes:
Friend function can be the friend of more than one classes.
Let us consider a simple example to understand this:
#include<iostream>
using namespace std;
class B; //without the previous declaration of class B compiler will
// not be able to decide what is B inside friend function
class A{
private:
int a;
public: // a friend function can be made either public or private
// during class declaration
friend void fun( A, B );
A(){ // to set value of a
a=23;
}
};
class B{
private:
int b;
public:
friend void fun( A, B );
B(){ // to set value of b
b=54;
}
};
void fun(A o1, B o2){ // friend function as friend of class A and B
cout<<"Sum is:"<<endl<<o1.a+o2.b<<endl;
}
int main(){
A obj1;
B obj2;
fun(obj1,obj2);
return 0;
}
Output:
Sum is:
77
Thanks for the great explanation.
ReplyDelete