Is the code order followed when initializing by writing the initialization list?

Asked 2 years ago, Updated 2 years ago, 141 views

In the initialization list, in the order in which you wrote down the code, I wrote the code thinking that initialization was happening.

For example,

class A{
private:
    OtherClass var1;
    AnotherClass var2;
public:
    A(OtherClass o, int y) :
    var1(o), var2(var1, y) { }

};

When we initialize var2 together, we have var1 va1 must be guaranteed to be initialized before var2 is initialized.

It works well on my computer, but I'm not sure if it's set as a standard, so I'm nervous

c++ gcc

2022-09-22 22:21

1 Answers

The order of initialization is

That is,

private:
    OtherClass var1;
    AnotherClass var2;

From

private:
    AnotherClass var2;
    OtherClass var1;

If you change it together, an error occurs because var2 starts initialization before var1.

C++ is implemented in this way because the destructor cleans up the members in the opposite order in which they are created.

There are multiple generators, but there is only one extinction If you implement a destructor based on the constructor, you should remember the order in which the members were created for each constructor In this case, the order of creation is always fixed because the declared order is the same for all objects.


2022-09-22 22:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.