Sunday, 29 March 2015

Friend Functions

The concept of encapsulation and data hiding dictate that non-member functions should not be allowed to access an object’s private and protected members. The policy is, if you are not a member you cannot get it. Sometimes this feature leads to considerable inconvenience in programming. Imagine that the user wants a function to operate on two different classes. At such times, it is required to allow functions outside a class to access and manipulate the private members of the class. At such times, it is required to allow functions outside a class to access and manipulate the private members of the class. In C++ this is achieved by using the concept of Friends.

C++ allows non-member functions to access even the private members of a class using friend functions or friend classes. It permits a function or all the functions of another class to access a different class’s private members.

Syntax

friend return_type function-name(arguments)
{
function body;
}

The function declaration must be prefixed by the keyword friend whereas the function definition must not. The function could be defined anywhere in the program similar to any normall C++ function. The functions that are declared with the keyword friend are called friend functions. A function can be friend to multiple
classes. A friend function possesses the following special characteristics.


? The scope of a friend function is not limited to the class in which it has been
   declared as a friend.
? A friend function cannot be called using the object of that class; it is not in the
   scope of the class. It can be invoked like a normal function without the use of
   any object.
? Unlike class member functions, it cannot access the class members directly.
   However, it can use the object and the dot operator with each member name to
   access both the private and public members.
? It can be either declared in the private part or the public part of a class without
   affecting its meaning.

Sample program

#include <iostream.h>
class one
{
int data;
public:
void setdata(void)
{
data = 100;
}
friend void show(one);
};
void show(one o)
{
cout<<o.data<<endl;
}
void main()
{
one A;
cout<<”object value is”;show();
}



No comments:

Post a Comment