2.0 C++ Inheritance

C++ Inheritance Overview

Inheritance in C++ means that a class can inherit properties and methods from another class. The inherited class is called the base class or parent class, and the class that inherits it is called a derived class or subclass.

C++ three inheritance

1. Public inheritance public

In public inheritance, both public and protected members of the base class can be accessed by derived classes, while private members of the base class can only be accessed by the base class, not derived classes.

2. Private inheritance private

In private inheritance, the public members, protected members, and private members of the base class cannot be accessed by the derived class, and can only be accessed in the member functions of the base class.

3. Protection inheritance protected

In protected inheritance, both public and protected members of the base class can be accessed by derived classes, but private members of the base class can still only be accessed by the base class, not derived classes.

Below I simply write a demo for readers to understand:
insert image description here

In addition, C++ also supports multiple inheritance, that is, a derived class can inherit multiple base classes at the same time.

It is recommended that readers should pay attention to avoid the problem of diamond inheritance when using multiple inheritance.

Because multiple derived classes inherit the same base class, it will lead to the problem of multiple base class subobjects in the derived class, readers must pay attention to this point.

Guess you like

Origin blog.csdn.net/qq_40240275/article/details/131243667