Home >Backend Development >C++ >What's the Order of Construction and Destruction in C Inheritance?

What's the Order of Construction and Destruction in C Inheritance?

DDD
DDDOriginal
2024-11-29 12:04:11765browse

What's the Order of Construction and Destruction in C   Inheritance?

Order of Construction and Destruction in Inheritance

Consider the following class hierarchy:

struct A {
    A() { std::cout << "A() C-tor" << std::endl; }
    ~A() { std::cout << "~A() D-tor" << std::endl; }
};

struct B : public A {
    B() { std::cout << "B() C-tor" << std::endl; }
    ~B() { std::cout << "~B() D-tor" << std::endl; }

    A a;
};

When an instance of B is created (as in int main() { B b; }), the construction and destruction order follows specific rules:

Construction Order:

  1. Base Class Constructor: The constructor of the base class (A) is called first.
  2. Member Field Construction: The member fields of the derived class (B) are constructed in the order they are declared. In this case, the instance a of class A is constructed.
  3. Derived Class Constructor: Finally, the constructor of the derived class (B) is called.

This translates to the following call order:

  • A()
  • A(a)
  • B()

Destruction Order:

  1. Derived Class Destructor: The destructor of the derived class (B) is called first.
  2. Member Field Destruction: The member fields of the derived class are destroyed in the reverse order they were constructed. In this case, the instance a of class A is destroyed.
  3. Base Class Destructor: Finally, the destructor of the base class (A) is called.

This results in the following destruction order:

  • ~B()
  • ~A(a)
  • ~A()

Therefore, the construction order starts with the base class, proceeds to the member fields, and ends with the derived class. The destruction order is the reverse of the construction order.

The above is the detailed content of What's the Order of Construction and Destruction in C Inheritance?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn