I know that you can initialize structs using list syntax:
struct Foo f = {a, b, c};
return f;
Is it possible to do this in one line as you would with classes and constructors?
Structure members can be initialized using curly braces '{}'. For example, following is a valid initialization.
No! We cannot initialize a structure members with its declaration, consider the given code (that is incorrect and compiler generates error).
Like a class, you can create an instance of a struct using the new keyword. You can either invoke the default parameterless constructor, which initializes all fields in the struct to their default values, or you can invoke a custom constructor.
If you want your struct to remain a POD, use a function that creates it:
Foo make_foo(int a, int b, int c) {
Foo f = { a, b, c };
return f;
}
Foo test() {
return make_foo(1, 2, 3);
}
With C++0x uniform initialization removes the need for that function:
Foo test() {
return Foo{1, 2, 3};
// or just:
return {1, 2, 3};
}
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