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:

  1. When an instance of LevelThree is created, the default constructor for LevelOne is called first, followed by the default constructor for LevelTwo, and finally the default constructor for LevelThree.
  2. When the instance of LevelThree is destroyed (either by the end of the main function or by explicitly calling delete), the destructor for LevelThree is called first, followed by the destructor for LevelTwo, and finally the destructor for LevelOne. 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.

C++ Class Inheritance: Constructor and Destructor Order in a Three-Level Hierarchy

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

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