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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With