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:

  1. The LevelOne constructor is called first, since it is the base class of LevelTwo.
  2. The LevelTwo constructor is called next, since it is the direct base class of LevelThree.
  3. The LevelThree constructor is called last, since it is the most derived class.
  4. When the main function returns and the obj object goes out of scope, the LevelThree destructor is called first.
  5. The LevelTwo destructor is called next, since it is the direct base class of LevelThree.
  6. Finally, the LevelOne destructor is called last, since it is the base class of LevelTwo.
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

原文地址: https://www.cveoy.top/t/topic/bFPy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录