(This question has been asked in GU Uni Dec 2018 for 7 Mark)
Friend Functions
Non-member function which is declared as a friend of particular class can have access to private data members of that class, in which it is declared as friend.
To make outside function (non-member) function friend of particular class we have to use ‘friend’ ‘keyword.
Simply, use the ‘friend’ keyword before function prototype. Consider below example,
#include <iostream> using namespace std; class Box { int width; //private public: void setData(int w) { width=w; } void getData() { cout<<"width:" <<width; } friend void display(Box ); }; void display(Box obj) //non member function { cout<< "Width from display function:"<< obj.width<<endl; } int main() { Box mybox; cout<<"Box Program"<<endl; mybox.setData(20); //erro mybox.getData(); display(mybox); return 0; }
OUTPUT
Box Program width:20Width from display function:20
Explain friend member function with example.