C++ Friend function is a function that is not a member of a class, even than it can access to the class's private, protected, and public members. Friend function works like a normal function. Friend function are not called using the member operators (. and ->). To declare a friend function, define its prototype within the class public section, preceding it with the friend keyword.
Example 1: Friend function. 1
#include <iostream.h> #include <conio.h> //friend function class A{ int a; public: void input1(); void output1(); friend void fun(A obj2); }; void A::input1() { cout<<"Enter no"; cin>>a; } void A::output1() { cout<<"Class A Output1"<<a; } void fun(A obj2) { cout<<"\nNormal function"<<obj2.a; } void main() { A obj; clrscr(); obj.input1(); obj.output1(); fun(obj); getch(); }
Advertisement
It is possible for one class to be a friend of another class. In CPP, member functions of friend class can access to the private, public members defined within other class.
Example 2: Friend class. 1
#include <iostream.h> #include <conio.h> class A { int a; public: void input1(); void output1(); friend class B; }; void A::input1() { cout<<"Enter no"; cin>>a; } void A::output1() { cout<<"Class A Output 1"; } class B{ int b; public: void output2(A); }; void B::output2(A obj1) { cout<<"Class B Output 2: " <<obj1.a; } void main() { A obj1; clrscr(); obj1.input1(); B obj2; obj2.output2(obj1); getch(); }
Advertisement