Create a three-level hierarchy of classes with default constructors along with destructors both of which announce themselves to cout Verify that for an object of the most derived type all three constr
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.
原文地址: https://www.cveoy.top/t/topic/bFPy 著作权归作者所有。请勿转载和采集!