Home > Backend Development > C++ > In C , How are Class Members Initialized and Destroyed?

In C , How are Class Members Initialized and Destroyed?

Mary-Kate Olsen
Release: 2024-11-08 10:02:02
Original
196 people have browsed it

In C  , How are Class Members Initialized and Destroyed?

Order of Initialization and Destruction of Class Members

In C , the order of initialization and destruction of class members plays a crucial role in object lifetime management. This behavior is commonly referred to as the "constructor and destructor call order."

Member Initialization Order

The C standard specifies that member variables are initialized in the order they are declared within the class definition. This order ensures that base classes are initialized before derived classes and that non-static data members are initialized in the order they appear.

Member Destruction Order

The reverse order applies to member destruction. Destructors are called in the reverse order of initialization, with derived class destructors called before base class destructors and non-static data member destructors called in the reverse order of their declaration.

Example

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;
}
Copy after login

When executed, this program produces the following output:

A::A
B::B
C::C
C::~
B::~
A::~
Copy after login

As expected, the members of Aggregate are initialized in the order A, B, then C, and their destructors are called in the reverse order.

Therefore, yes, C guarantees that members are initialized in the order of declaration and destroyed in reverse order for both class members and aggregate types.

The above is the detailed content of In C , How are Class Members Initialized and Destroyed?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template