Friend Function





Friend function

The concept of encapsulation and data hiding indicates that non member functions should not be able to access the private and protected data. But, in some situation, if it is needed to be shared private or protected data, then it can be made possible with the help of a “friend function”. That means, a function has to be declared as friend function to give it the authority to access to the private data.

Hence, friend function is not a member function of the class but can access all public, protected and private members of that class.

The general syntax of the friend function is:-

Friend return_type function_name (arguments);

Where friend is a keyword.

[Note:- Friend is a special mechanism for letting non-member function access private data. Hence, we can say that friend violet concept of encapsulation in object oriented programming].

A program accessing Private data’s using Friend function.

#include<iostream.h>

#include<conio.h>

Class alpha

{

Private:

Int data;

Public:

Alpha ()     // constructor with no argument

{

data=3;

}

Friend int gamma (alpha, beta); // friend function

};

Class beta

{

Private:

Int data;

Public:

Beta ()       //constructor with no argument

{

Data=7;

}

Friend int gamma (alpha, beta);   // friend function

}

Int gamma (alpha a, beta b)    // definition of friend function

{

Return (a. Data + b.data);

}

Void main ()

{

Alpha aa;

Beta bb;

Cout<<gamma (aa,bb);    //call the function

getch ();

}



Related posts:

  1. Access Specifier In C++ Access specifier A key feature of object oriented programming is...
  2. Derivation in C++ Types of derivation Inheritance is a process of creating a...
  3. Class In C++ Class in c++ Class is a group of similar object....
  4. Defining Member Function In C++ Class methods definitions  (Defining the member functions) Member functions can...
  5. Class Hierarchies Class Hierarchies The relationship between a base ad derived classes...