Monday, April 27, 2015

Friend function simple example in C++

A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.
A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends.
To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend as follows:

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
class access
{
// String Variable declared as internal
public:
void SetName(string Name);
friend void print(access objAcess);
private:
string name;
};
void access::SetName(string Name)
{
name = Name;
}

void print(access objAcess)
{
cout << "\nMy name is " << objAcess.name;
}

void main( )
{
access objAcess;
objAcess.SetName("Sreeyush");
print(objAcess);
    _getch();

}

No comments:

Post a Comment