1. The basic concepts and syntax of inheritance
Overview of inheritance and derivation
-
Inheritance and derivation are the same process viewed from different angles
-
The process of maintaining the characteristics of the existing class and constructing a new class is called inheritance
-
The process of creating new classes by adding their own characteristics to existing classes is called derivation .
-
-
The inherited existing class is called the base class (or parent class)
-
Derive a new class called School Health class (or subclass)
-
The base class that directly participates in deriving a certain class is called the direct base class
-
The base class of the base class or even the higher base class is called the indirect base class
Purpose of inheritance and derivation
-
The purpose of inheritance: to achieve design and code reuse.
-
The purpose of derivation: When a new problem appears and the original program cannot be solved (or cannot be completely solved), the original program needs to be modified.
The definition of derived classes in single inheritance
-
grammar
class Derived class name: inheritance method base class name
{
Member declaration;
}
-
Example
class Derived: public Base //公有继承Base类
{
public:
Derived ();
~Derived ();
};
The definition of derived classes in multiple inheritance
-
grammar
class Derived class name: inheritance mode 1 base class name 1, inheritance mode 2 base class name 2,...
{
Member declaration;
}
Note: Each "inheritance method" is only used to limit the inheritance of the base class that follows it.
-
Example
class Derived: public Base1, private Base2
{
public:
Derived ();
~Derived ();
};
Derived class composition
-
Inherited base class members: By default, a derived class contains all members of the base class except for the constructor and destructor. C++11 stipulates that you can use the using statement to inherit the constructor of the base class.
-
Modification of base class members: If a derived class declares a new member with the same name as a member of a base class, the new derived member hides or covers the outer members with the same name.
-
Adding new members: The addition of new members to the derived class makes the derived class develop in function.