Does friend function follows access specifier rule in C++

No, friend functions do not follow access specifier rules as they are not members function. Friend function declared in any access specfier can access private data of the class using object.
#include<iostream>
using namespace std;
class sample
{
private:
        int a;
private:
        void privateNormalFunction(){};
private:
        friend void f1(sample);
protected:
        void friend f2(sample);
public:
        friend void f3(sample);
};
void f1(sample s)
{
s.a=10;
cout<<"f1::a"<<s.a<<endl;
}
void f2(sample s)
{
s.a=10;
cout<<"f2::a"<<s.a<<endl;
}
void f3(sample s)
{
s.a=10;
cout<<"f3::a"<<s.a<<endl;
}
int main()
{
sample s;
f1(s);
f2(s);
f3(s);
return 0;
}                                                                                                                                               
                                                                                                                                                

No comments:

Post a Comment