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:

  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.

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.

C++ Class Hierarchy: Constructors and Destructors with Output

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

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