1.C++ access control
(1). public
public means all member declarations that follow are available to everyone.
(2) private
The private keyword means that no one can access that member except you, the creator of the type.
(3).protected
This keyword acts just like private, with one exception--inherited.
2. Friends
In C++ ,there is an another keywork named friend which means that a function is not the class's member but it has access to class's private member.
class A
{
private:
int a;
public:
A(int m){a = m;};
int getA();
friend int fA(A& tmp,int x);
};
int A::getA()
{
return a;
}
int fA(A& tmp,int x)
{
return tmp.a = x;
}
In the example, fA() can modify A's private variable a. And also, you can grant access to an another class's function like this:
class A;
class B
{
public:
void modifyA(A& tmp);
int test(A& tmp);
};
class A
{
private:
int a;
public:
A(int m){a = m;};
int getA();
friend void B::modifyA(A& tmp);
};
int A::getA()
{
return a;
}
void B::modifyA(A& tmp)
{
tmp.a = 10;
}
int B::test(A& tmp)
{
//return tmp.a; //error, a is a private
return tmp.getA();
}
How to make a class nested automaticaly gave access to private members? To accomplish this, you must follow a particular form: first, declare(without defining) the nested class, then declare it as a friend, and finally define the class.
class A
{
private:
int a;
public:
class B;
friend class B;
class B{
public:
void modifyA(A& tmp);
};
};
void A::B::modifyA(A& tmp)
{
tmp.a = 10;
}