public, private and protected in c++

Three characteristics of classes: encapsulation, inheritance, polymorphism

Encapsulation, the role of public and private is to achieve this purpose. Outside the class, public members can be accessed but private members cannot be accessed.
Private members can only be accessed by class members and friend members.

Inheritance, the role of protected is to achieve this purpose. Protected members can be accessed by derived class objects, but cannot be accessed by members outside the class.

Public inheritance, base class public members, protected members, access attributes of private members become: public, protected, private respectively in the derived class.
Protected inheritance, base class public members, protected members, access attributes of private members become: protected, protected, private respectively in the derived class.
Private inheritance, base class public members, protected members, access attributes of private members become: private, private, private respectively in the derived class.

https://zhuanlan.zhihu.com/p/70758317

public: Accessible both inside and outside the class.
protected: Accessible within the class, not accessible outside the class.
private: It can be accessed within the class, can be accessed by friends, and cannot be accessed outside the class.

When inheriting:
class A: public B: public, protected, private or public, protected, private, keep the original characteristics, and private cannot be accessed by derived classes.
class A: protected B: public, protected, and private become protected, protected, and private, maintaining the original characteristics, and private cannot be accessed by derived classes.
class A: private B: public, protected, and private become private, private, and private, and private cannot be accessed by derived classes.

The base class is private, and derived classes cannot access private members of the base class!
The base class is private, and derived classes cannot access private members of the base class!
The base class is private, and derived classes cannot access private members of the base class!

Guess you like

Origin blog.csdn.net/threestooegs/article/details/129343763