Home >Backend Development >C++ >What's the Order of Constructor and Destructor Calls in C Inheritance?

What's the Order of Constructor and Destructor Calls in C Inheritance?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-05 20:15:43972browse

What's the Order of Constructor and Destructor Calls in C   Inheritance?

Order of Constructor and Destructor Calls in Inheritance

When defining inherited classes, it's crucial to understand the sequences in which constructors and destructors are invoked. Consider the following example:

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

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

    A a;
};

Construction Order:

  1. Base Class Constructor: The constructor of the base class (A) initializes the base portion of the derived object.
  2. Member Field Construction: Since B has a field of type A, its constructor will call the constructor for this field.
  3. Derived Class Constructor: Finally, the constructor of the derived class (B) completes the initialization of the object.

Thus, the order of construction is:

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

Destruction Order:

Destructors are invoked in the reverse order of construction:

  1. Derived Class Destructor: The destructor of the derived class (B) starts the cleanup process.
  2. Member Field Destruction: The field of type A (a) is destroyed.
  3. Base Class Destructor: Lastly, the destructor of the base class (A) completes the destruction.

The order of destruction is:

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

Initializer List:

Even if no explicit initializer list is defined in B, a default initialization list is automatically generated by the compiler. This list initializes the base class (A) and the member field (a) using their default constructors.

In conclusion, the order of constructor and destructor calls in inheritance follows specific rules: constructors initialize base classes first, then member fields, and finally the derived class. Destructors invoke the cleanup process in reverse order. Understanding these rules is essential for writing robust code when using inheritance.

The above is the detailed content of What's the Order of Constructor and Destructor Calls 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