C++ Class Inheritance: Constructor and Destructor Order in a Three-Level Hierarchy
Here is a three-level hierarchy of classes with default constructors and destructors:
#include <iostream>
class LevelOne {
public:
LevelOne() {
std::cout << 'LevelOne constructor called' << std::endl;
}
~LevelOne() {
std::cout << 'LevelOne destructor called' << std::endl;
}
};
class LevelTwo : public LevelOne {
public:
LevelTwo() {
std::cout << 'LevelTwo constructor called' << std::endl;
}
~LevelTwo() {
std::cout << 'LevelTwo destructor called' << std::endl;
}
};
class LevelThree : public LevelTwo {
public:
LevelThree() {
std::cout << 'LevelThree constructor called' << std::endl;
}
~LevelThree() {
std::cout << 'LevelThree destructor called' << std::endl;
}
};
To verify that all three constructors and destructors are automatically called for an object of the most derived type, we can create an instance of LevelThree and observe the output:
int main() {
LevelThree obj;
return 0;
}
The output will be:
LevelOne constructor called
LevelTwo constructor called
LevelThree constructor called
LevelThree destructor called
LevelTwo destructor called
LevelOne destructor called
The order in which the calls are made is as follows:
- When an instance of
LevelThreeis created, the default constructor forLevelOneis called first, followed by the default constructor forLevelTwo, and finally the default constructor forLevelThree. - When the instance of
LevelThreeis destroyed (either by the end of themainfunction or by explicitly callingdelete), the destructor forLevelThreeis called first, followed by the destructor forLevelTwo, and finally the destructor forLevelOne. This is the reverse order of the constructors, since destruction happens in the opposite order of construction.
Note that the constructors and destructors for each class in the hierarchy are automatically called by the compiler, without the need for any explicit calls in the main function or elsewhere in the code. This is an example of the automatic resource management provided by C++'s object-oriented features.
原文地址: https://www.cveoy.top/t/topic/m9Sa 著作权归作者所有。请勿转载和采集!