Home >Backend Development >C++ >How are member constructors and destructors called in C inheritance and aggregation?

How are member constructors and destructors called in C inheritance and aggregation?

Barbara Streisand
Barbara StreisandOriginal
2024-11-08 08:02:01250browse

How are member constructors and destructors called in C   inheritance and aggregation?

Order of Member Constructor and Destructor Calls

In C , the order of member constructor and destructor calls is a fundamental aspect of object initialization and destruction. It ensures proper initialization and cleanup of class members, especially in situations involving inheritance and aggregation.

Consider the following program:

#include <iostream>
using namespace std;

struct A {
    A() { cout << "A::A" << endl; }
    ~A() { cout << "A::~" << endl; }
};

struct B {
    B() { cout << "B::B" << endl; }
    ~B() { cout << "B::~" << endl; }
};

struct C {
    C() { cout << "C::C" << endl; }
    ~C() { cout << "C::~" << endl; }
};

struct Aggregate {
    A a;
    B b;
    C c;
};

int main() {
    Aggregate a;
    return 0;
}

When executed, this program produces the following output:

A::A
B::B
C::C
C::~
B::~
A::~

This output demonstrates that the member constructors are called in the order of declaration, and the member destructors are called in the reverse order of declaration.

The C Standard guarantees this order under the following conditions:

  1. Initialization Order: Direct base classes and non-static data members are initialized in the order they appear in the class definition.
  2. Destruction Order: Destructors for derived and base classes are called in the reverse order of the initialization order.

In this example, the Aggregate class contains members a of type A, b of type B, and c of type C. When the Aggregate constructor is called, the members are initialized in the order a, b, and c. Correspondingly, when the Aggregate destructor is called, the members are destroyed in the reverse order, c, b, and a.

Understanding the order of member constructor and destructor calls is crucial for correct object lifetime management in C , especially when working with inheritance and complex class structures.

The above is the detailed content of How are member constructors and destructors called in C inheritance and aggregation?. 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