Thursday, Aug 16th

Last update12:59:40 PM GMT

Friend Functions and Friend Classes

Write e-mail

Friend Function in C++Friend functions are functions defined outside a class (ie, they are not member functions), but which the class declares to be friends so that they can access the class's non-public members even from outside the class. Normally a function which is not a member of a class cannot access private or protected data of that class; neither can an external class. Though this is perfectly inline with the OOP concept of data-hiding, but in some cases programmers need to have a different behaviour. Though C++ provides the programmer with the freedom to make use of friend functions and friend classes, still they should be wisely used as their use violates encapsulation theory. An extensive use of friend functions is in Operator Overloading about which we will study later.

argaiv1770

FRIEND FUNCTION

When a function needs to operate on private data in object from a class, the function can be declared as a friend in that class, taking object of the class as argument in the friend function:

class A
{
private:
int x,y;
public:
void f()
{
x=1;
y=2;
}
friend int func(A a);
};

int func(A aa)
{
return (aa.x + aa.y);
}

In the above example, func is an external function defined outside the class A. The line:

friend int func(A a);

inside the class just declares the function func() to be a friend of the class A in the sense that it can access the non-public data (variables x and y), without being the member function of the class.And this is what the implementation of func() does. It uses the x and y variables of the object aa of class A passed as argument to it.

  1. Even though the friend function func() is declared under the public scope yet one thing to note here is that a class doesn't control the scope of friend functions so friend function declarations are usually written at the beginning of a .h file. Public and private don't apply to them. Since friend function is not a member function of the class, hence it cannot use this pointer inside it.
  2. A possible advantage of friend functions is efficiency since they access the private members directly they avoid the overhead of calling explicit get-member functions.

 

FRIEND CLASS

On the same lines as friend functions we also have friend classes. As it can be deduced from the discussion till now, a friend class has full access to non-public members of another class without being a member of that class.

class A
{
private:
//...(statements)
public:
//...(statements)
friend class B;
}

Here class B will have full access to the non-public members of class A. The declaration of class B is not shown above and is immaterial.

Share this post



Add comment

Please refrain from using slang or abusive language in the comments.
To avoid waiting for your comment to be published after being reviewed, please log in as a registered user.


Security code
Refresh

Web Hosting