Derived and base classes

One of the main goals of C++ is to provide code reuse, and class inheritance is one of the important ways to achieve this goal. When one class is derived from another, the original class is called the base class and the inherited class is called the derived class.

1. The derived class object stores the data members of the base class 
2. The derived class object can use the methods of the base class 

 

Member access rights regarding the three inheritance methods:

 

 

1. The private member of the base class cannot be accessed in the derived class. If the base class member does not want to be accessed directly outside the class, but needs to be accessible in the derived class, it is defined as protected. It can be seen that the protected member qualifier appears because of inheritance.


2. Public inheritance is an interface inheritance, maintaining the is-a principle, the members available to each parent class are also available to subclasses, because each subclass object is also a parent class object.


3. Protced/private inheritance is an implementation inheritance. Some members of the base class do not completely become part of the subclass interface. It is the has-a relationship principle. Therefore, these two inheritance relationships will not be used under special circumstances. In most scenarios, public inheritance is used.


4. Regardless of the inheritance method, the public and protected members of the base class can be accessed within the derived class, and the private members of the base class exist but are not visible (cannot be accessed) in the subclass.


5. When using the keyword class, the default inheritance method is private, and when using struct, the default inheritance method is public, but it is best to show the inheritance method.


6. In practice, public inheritance is generally used, and protected/private inheritance is used in very few scenarios.

 

 

References:

https://blog.csdn.net/qq_33724710/article/details/51635331

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324492849&siteId=291194637