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

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

Barbara Streisand
Release: 2024-12-21 10:51:16
Original
727 people have browsed it

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

Initialization Order of Non-Static Data Members

In this scenario, we have two non-static data members, a and b, declared within the class X. A common question arises: in what order are these data members initialized when the constructor for X is invoked?

To answer this question, we turn to section 12.6.2 of the C Standard, which outlines the initialization order of class members:

5 Initialization shall proceed in the following order:
-- First, and only for the constructor of the most derived class as described below, virtual base classes shall be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes...
-- Then, direct base classes shall be initialized in declaration order as they appear in the base-specifier-list...
-- Then, nonstatic data members shall be initialized in the order they were declared in the class definition...
-- Finally, the body of the constructor is executed...
Copy after login

Based on this rule, the order of initialization of a and b is determined solely by their placement within the class definition. Since a precedes b, it will be initialized first. This holds true regardless of any explicitly specified order of member initialization within the constructor body.

Therefore, in this case, the constructor of A will be called before the constructor of B when the constructor of X is invoked.

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