Friend Functions

A function that is allowed to access private/protected members of a class from outside the class – Friend Function.

  • Defined outside class’s scope
  • Right to access non-public members
  • Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

Code in C++

#include<iostream>
using namespace std;
class B;
class A
{
int a;
public:
A()
{
a=9;
}
friend void show(A,B);
};
class B
{
int b;
public:
B()
{
b=8;
}
friend void show(A,B);
};
void show(A x,B y)
{
int r;
r=x.a+y.b;
cout<<r;
}
void main()
{
A obj1;
B obj2;
show(obj1,obj2);
getchar();
getchar();
}

Print Friendly

Share this with your friends

One Comment to “Friend Functions”

  1. Please teach the rest of these internet hoonagils how to write and research!

Leave a Reply

Your email address will not be published. Required fields are marked *