Using Friend Class
#include <stdafx.h>
#include <iostream>
#include <string>
using namespace std;
class TestFriend
{
// Using friend class.
int i; // Here i is a private member of the class TestFriend.
friend class MyClass; // MyClass is made a friend of the class TestFriend.
};
class MyClass //A friend class is a class whose members have access to the private or protected members of another class
{
public:
void display(int a)
{
TestFriend tf;
tf.i=a; // Trying to access the private member i of the class TestFriend.
cout<< "Value of the private member :" << tf.i;
}
};
int main()
{
MyClass mc;
mc.display(100);
return 0;
}
Output:
error C2248: 'TestFriend::i' : cannot access private member declared in class 'TestFriend'