The C++ program example on how to use the friend keyword to access the private and protected class member

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the function with friend keyword to access the private and protected class member in C++ programming

To show: How to use the friend keyword in accessing the the private and protected class member in C++ programming

 

// using the friend (keyword) function

// The friend keyword allows a function or class to gain access to the private and protected

// members of a class. You can declare friend functions or friend classes to access not only

// public members but also protected and private class members.

#include <iostream>

using namespace std;

 

class SampleFriend

{

// private member variable

int i;

// friend_funct is not private, even though it's declared in the private section

friend int friend_funct(SampleFriend *, int);

public:

// constructor

SampleFriend(void) { i = 0;};

int member_funct(int);

};

 

// implementation part, both functions access private int i

int friend_funct(SampleFriend *xptr, int a)

{

return xptr->i = a;

}

int SampleFriend::member_funct(int a)

{

return i = a;

}

 

int main(void)

{

// note the difference in function calls

SampleFriend xobj;

 

cout<<"\nfriend_funct(&xobj, 10) is "<<friend_funct(&xobj, 10)<<"\n\n";

cout<<"xobj.member_funct(10) is "<<xobj.member_funct(10)<<endl;

 

return 0;

}

 

Output example:

 

friend_funct(&xobj, 10) is 10

xobj.member_funct(10) is 10

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index