Digital Music

12/25/2009

Friend Function in C++

any data declared in the class are private, and not accessible outside of class. A function that is not in the class will never be able to access the data in a class that is private. But there are certain cases where we need to access the private data.

Class will give permission to other functions outside the class to read the data, namely by making it a friend function of the class.

• friend function defined outside of the class's scope However the have access to all the members of the class

• once a function declared as a friend, a function that can access private data from these classes.

• Declaration friend funcion dg keyword 'friend'

C++ Tutorial - Friend function sample:
#include
//Declaration of the function to be made as friend for the C++ Tutorial sample
int AddToFriend(int x);
class CPP_Tutorial
{
int private_data;
friend int AddToFriend(int x);
public:
CPP_Tutorial()
{
private_data = 5;
}
};
int AddToFriend(int x)
{
CPP_Tutorial var1;
return var1.private_data + x;
}
int main()
{
cout << "Added Result for this C++ tutorial: "<< AddToFriend(4)<< iostream.h >
class CPP_Tutorial
{
int private_data;
friend class friendclass;
public:
CPP_Tutorial()
{
private_data = 5;
}
};
class friendclass
{
public:
int subtractfrom(int x)
{
CPP_Tutorial var2;
return var2.private_data - x;
}
};
int main()
{
friendclass var3;
cout << "Added Result for this C++ tutorial: "<< var3.subtractfrom(2)<
}

0 komentar:

Post a Comment