Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization during construction?

I wrote the following code:

struct A{
    int a;
    int b;
    A(int c): a(c), b(a){ }
};


int main()
{
    A b(10);
}

Now, I'm not sure about initializing b with a as a(c), b(a). Is it OK to do so or may cause UB?

like image 493
stella Avatar asked Oct 15 '15 04:10

stella


1 Answers

Yes, this is okay. Members are initialized in the order they are declared in the class. Note that the order of the initializers doesn't matter, so this would also work (but would not be good practice):

struct A{
    int a;
    int b;
    A(int c): b(a), a(c) { }
};

but this would not work:

struct A{
    int b;
    int a;
    A(int c) : a(c), b(a) { } 
};

Some compilers can give you a warning if the initializer order doesn't match the declaration order.

like image 104
Vaughn Cato Avatar answered Oct 02 '22 04:10

Vaughn Cato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!