Home >Backend Development >C++ >What is the order of member constructor and destructor calls in C ?

What is the order of member constructor and destructor calls in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-11-08 03:33:02607browse

What is the order of member constructor and destructor calls in C  ?

Order of Member Constructor and Destructor Calls: A C Specification

In C , the order of initialization and destruction of class members is crucial for managing object lifetimes and memory allocation efficiently. This article sheds light on the specifics of this process, as defined by the C language standard.

Consider the following code snippet:

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 this code executes, the constructor and destructor calls will occur in a specific order.

Member Initialization Order:

As per C 14 standard section 12.6.2:

  • Static data members are initialized first, in the order of declaration.
  • Non-static data members are initialized next, also in the order of declaration. Here, member a is initialized first, followed by b and then c.

Therefore, the expected output for member initialization is:

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

Member Destruction Order:

The order of member destruction is the reverse of initialization:

  • Non-static data members are destroyed in the reverse order of declaration.
  • Static data members are destroyed last.

The expected output for member destruction is thus:

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

This confirms that C guarantees the order of member construction and destruction as specified in the standard. Members are initialized in declaration order and destroyed in reverse declaration order, ensuring proper memory management and object lifecycle. Understanding these rules is essential for writing efficient and correct C code.

The above is the detailed content of What is the order of member constructor and destructor calls in C ?. 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