Inheritance: Construct and destruct the Child class inherits from the Parent class
Class Child: public ParentCopy the code
So, when creating a subclass object :(the compiler runs by default) when subclass object construction, the constructor of the parent class is called first, then the constructor of the parent class is called when subclass object destructor is called, then the constructor of the parent class is called
When a parent class has multiple constructors, one of the constructors can be explicitly called. If not explicitly called, the “default constructor” of the parent class is called.
When a class is inherited, the parent’s destructor should be declared virtual, otherwise there are potential problems
Class Parent {virtual ~Parent(){}// declare virtual};Copy the code
Consider the following scenario:
Parent *p=new Child(); delete p; // Whose destructor is called?Copy the code
If the destructor is not identified as virtual, it is potentially dangerous and may directly cause the program to crash.
(1) The size of a class is determined by its member variables. (This struct works the same way.) The size of a class is independent of the number of member functions it has. If a member function is declared virtual, the size of the class will be micro-sized. (This change is at the compiler’s discretion and typically adds 4 bytes.)
- Describes inheritance relationships in which the constructor and destructor of the parent class are called
- When a class is inherited from another class, the destructor of the parent class should be declared virtual. (Note: This is not necessary if the class was designed to be uninherited.)