Home > Backend Development > C++ > What's the Initialization Order of Non-Static Data Members in C Classes?

What's the Initialization Order of Non-Static Data Members in C Classes?

Mary-Kate Olsen
Release: 2024-12-18 15:12:14
Original
380 people have browsed it

What's the Initialization Order of Non-Static Data Members in C   Classes?

Initialization Order of Non-Static Data Members in C

When creating a new instance of a class with non-static data members, the order in which they are initialized is crucial for proper object construction.

In this scenario, let's consider the following code:

class A {};
class B {};
class X
{
    A a;
    B b;
};
Copy after login

The question arises: when the constructor of class X is invoked, which constructor (A or B) is called first? Does their position within the class definition determine the order?

According to the C Standard, section 12.6.2, the initialization order is as follows:

  • First, virtual base classes are initialized (not applicable in this case).
  • Direct base classes are initialized in declaration order (also not applicable here).
  • Non-static data members are initialized in the order they appear in the class definition.
  • Finally, the constructor body is executed.

Therefore, in the provided code, the non-static data members a and b are initialized in the order they are declared, which is a first followed by b. The constructor of A will be called before the constructor of B.

In summary, the order of initialization for non-static data members is determined by their declaration order within the class definition, not by their placement within the constructor body.

The above is the detailed content of What's the Initialization Order of Non-Static Data Members in C Classes?. 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