Why C++ forces initialization of member variables to be in the order of the declaration
Asked Answered
H

1

21

I know that in C++ the declaration of members in the class header defines the initialization order. Can you tell me why C++ choose this design? Are there any benefits to force the initialize order instead of following the initializer list?

Haihaida answered 30/6, 2021 at 5:21 Comment(0)
I
34

Constructors could be overloaded while destructor can't. If data members could be initialized in different order for different constructors, then the destructor can't guarantee to perform destruction on data members in the reverse order of their construction (for objects constructed by different constructors).

Instillation answered 30/6, 2021 at 5:25 Comment(3)
...and if you must have that kind of control, there are ways to remove a member's initialization and destruction from these mechanisms and do it all yourself, but that has both (generally) runtime overhead and conceptual overhead.Cherlynchernow
@Cherlynchernow Agreed with conceptual overhead, but why runtime? If you have a member storage buffer and then use placement new in the constructor, what overhead this will have with respect to traditional member variable?Macaluso
@DanielLangr I said "generally", not always, though if you end up doing such a thing I do find it likely that you'll need to store some extra data for bookkeeping. E.g. if you wanted to replicate the default destruction in reverse order of construction but have the order of construction vary somehow, then you must store the order in which you did it at construction and then branch on that at destruction. Or if you might sometimes not have a member constructed then you must remember such at destruction (e.g. std::optional/std::variant).Cherlynchernow

© 2022 - 2024 — McMap. All rights reserved.