GENERAL CONCEPT :
- We know that only member functions can access the PRIVATE data of a class. This is the essence of data-encapsulation.
- However, sometimes we want to make an exception to this rule to avoid programming inconvenience. At such times we allow functions outside a class to access and manipulate class’s data members.
- To achieve this, C++ provides a keyword called ‘friend’.
- It permits a function or all the functions of another class to read and modify original class’s private data members.
DEFINITION :
Therefore, if a function is defined as a friend function in C++ to a class, then the protected and private data of this class can be accessed using this function.
SYNTAX :
(1) Declaration : class class_name { friend data_type function_name(argument/s); // syntax of friend-funct. }; (2) Definition : // Just similar as any normal function. /* The function definition does not use either the keyword 'friend' or scope resolution operator(::). */
RULES :
- The concept of friends is not there in Java.
- The declaration of the friend function must be present in the class body.
- It cannot be called using the object (using ‘.’ operator) as it is not in the scope of that class.
- It can be invoked like a normal function without using the object.
- It can be declared either in the private or the public part.
- It cannot access the data-member-names directly and has to use an object name and ‘.’ operator with the member name.
EXAMPLE :
#include<iostream> using namespace std; class two; class one { private : int data1; public : one() { data1 = 100;} friend access_both(one, two); }; class two { private : int data2; public : two() { data2 = 200;} friend access_both(one, two); }; int access_both(one a, two b) { return (a.data1 + b.data2); } int main() { one a; two b; cout<<access_both(a,b)<<endl; return 0; } // OUTPUT : 300
NOTE :
Friends should be used only for limited purpose – if too many functions are declared as friends of a class with protected or private data, it lessens the value of encapsulation of classes in object-oriented programming.
Categories: C++
Leave a Reply