New
FRIEND FUNCTION IN C++ :
The concepts of encapsulation and data hiding dictate that nonmember functions should not be able to access an object’s private or protected data. The policy is, if you’re not a member, you can’t get in. However, there are situations where such rigid discrimination leads to considerable inconvenience.
The following properties explain the concept of Friend Function clearly4;
1-Friend function is not a member function of a class to which it is a friend.
2-Declare in class with "Friend " keyword.
3-It must be define outside the class but declare inside the class.
4-It can not access member of the class directly.
5-It has no caller Object.
6-It should not be define with membership label.
For Example:
#include<iostream>
using namespace std;
class B; /*formal declaration of class B because of its use in class */
class A
{
private:
int a;
public:
A():a(3) { }
friend void fun(A,B);
/*friend function can be declare in more then one class and it become friend of those /////classes in which it is declare /////it can be declare either in private or public because it is not a member function*/
};
class B
{
private:
int b;
public:
B():b(9) { }
friend void fun(A,B);
/*friend function also declare here to make it friend of this class/////it can be declare either in private or public because it is not a member function*/
void fun(A o1,B o2)
/*friend function always define outside the class and having no membership label*/
{
cout<<"sum is "<<o1.a+o2.b<<endl;
}
int main() //main function
{
A a1;
//Declare Object with Type of Class name A
B b1;
fun(a1,b1);
/*friend function can access the private members of more than one class *////* simultaneously like here it access the a private member of class A and b of class B */
}
No comments:
Post a Comment