При использовании класса действительно нет разницы между защищенными и частными членами. Ни один из них не доступен для всего, что использует класс.
class A {
private: int privateNum;
protected: int protectedNum;
public: int publicNum;
void SetNumbers(int num) {
privateNum = num; //valid, private member can be accessed in member function
protectedNum = num; //valid, protected member can be accessed in member function
}
};
void main() {
A classA;
classA.privateNum = 1; //compile error can't access private member
classA.protectedNum = 1; //compile error can't access protected member
classA.publicNum = 1; //this is OK
classA.SetNumbers(1); //this sets the members not accessible directly
}
Разница вступает в силу, когда вы наследуете класс с защищенными членами.
class B : public A {
};
Все закрытые члены базового класса по-прежнему являются закрытыми и не будут доступны для производного класса. Защищенные члены, с другой стороны, доступны для унаследованного класса, но все еще недоступны за пределами унаследованного класса.
class B : public A {
public:
void SetBNumbers(int num) {
privateNum = num; //compile error, privateNum can only be accessed by members of A, not B
protectedNum = num; //this works, as protected members can be accessed by A and B
}
};
void main() {
B classB;
classB.publicNum = 1; //valid, inherited public is still public
classB.protectedNum = 1; //compile error, can't access protected member
classB.privateNum = 1; //compile error, B doesn't know that privateNum exists
classB.SetBNumbers(1); //this sets the members not accessible directly
}