C++ Class Hierarchy: Constructors and Destructors with Output
This article explores the automatic invocation of constructors and destructors in a three-level C++ class hierarchy. We'll demonstrate the order of execution and provide a code example to illustrate these concepts.
Here's an example of the three-level hierarchy of classes:
class LevelOne {
public:
LevelOne() { cout << 'LevelOne constructor called.' << endl; }
~LevelOne() { cout << 'LevelOne destructor called.' << endl; }
};
class LevelTwo : public LevelOne {
public:
LevelTwo() { cout << 'LevelTwo constructor called.' << endl; }
~LevelTwo() { cout << 'LevelTwo destructor called.' << endl; }
};
class LevelThree : public LevelTwo {
public:
LevelThree() { cout << 'LevelThree constructor called.' << endl; }
~LevelThree() { cout << 'LevelThree destructor called.' << endl; }
};
To verify that for an object of the most derived type, all three constructors and destructors are automatically called, we can create an object of the LevelThree class and observe the output:
int main() {
LevelThree obj;
return 0;
}
This should output:
LevelOne constructor called.
LevelTwo constructor called.
LevelThree constructor called.
LevelThree destructor called.
LevelTwo destructor called.
LevelOne destructor called.
The order of the calls is as follows:
- The
LevelOneconstructor is called first, since it is the base class ofLevelTwo. - The
LevelTwoconstructor is called next, since it is the direct base class ofLevelThree. - The
LevelThreeconstructor is called last, since it is the most derived class. - When the
mainfunction returns and theobjobject goes out of scope, theLevelThreedestructor is called first. - The
LevelTwodestructor is called next, since it is the direct base class ofLevelThree. - Finally, the
LevelOnedestructor is called last, since it is the base class ofLevelTwo.
This demonstrates the fundamental principle of constructor and destructor execution in C++ inheritance. Constructors are called in the order of the class hierarchy from base to derived, while destructors are called in the reverse order from derived to base.
原文地址: https://www.cveoy.top/t/topic/m9R2 著作权归作者所有。请勿转载和采集!