The three types of inheritance in C++ are public protected and private
- 2020-04-02 01:38:03
- OfStack
Three types of access
Public: Can be accessed by any entity
Protected: Only subclasses and their member functions are allowed access
Private: Only member functions of this class are allowed access
Three ways of inheritance
Public inheritance
Protect inheritance
Private inheritance
Combination of results
In the base class
Public & public inheritance = > public
Public & protected inheritance = > protected
Public & private inheritance = > private
Protected & public inheritance =
>
protected
Protected & protected inheritance = > protected
Protected & private inheritance = > private
Private & public inheritance =
>
Subclass has no access
Private & protected inheritance = > Subclass has no access
Private & private inheritance = > Subclass has no access
It can be seen from the above combination results
1. Public inheritance does not change the access rights of the members of the base class
2. Private inheritance makes all members of the base class have private access in the subclass
3. Protected inheritance changes the public member of the base class into a protected member of the subclass.
4. The private member in the base class is not affected by the inheritance mode, and the subclass is never entitled to access.
In addition, when using private inheritance, there is another mechanism: granting access.
We already know that when a base class is inherited in private, its public and protected members become private members in subclasses. In some cases, however, one or more inherited members need to have their access restored in the base class in a subclass.
C++ supports this in two ways
Method a, Use using statements, which is the way the C++ standard recommends using them
Method 2, Use an access declaration in the form of base-class::member; , at the appropriate access declaration in the subclass. (note, access can only be restored, not increased or decreased)
Why do you define public protect private in c++?
Some of the things we need to show the outside world, which is the external interface, are public. If there is no external interface, the work we do will be meaningless.
If we don't want anyone else to know the internal implementation details, it's private, for example:
public:
count()
{
mycount();
}
private:
mycount();
So, count is the external interface, and when we implement it, we don't want the outside world to know how to implement it, so we just use private to prevent it from using mycount!
If we don't want anyone to know, what we want our children to know (inheritance is involved here), we can use it as protected!
In this case, private is private, protected is to let the child know, public is public!