I'm trying to find a way to statically initialize a struct which extends another struct.
If I have a struct in c++:
struct aStruct {
int a;
int b;
};
I can statically initialize an instance of this with:
aStruct aStructInst = { 1, 2 };
I can also extend this struct if I want a child object to store additional information:
struct bStruct : aStruct {
int c;
};
Is there any way to statically initialize an instance of bStruct
? I've tried a few variations but no luck yet. Static initialization is important in my use-case to keep (all of) the data out of RAM, which is very limited (embedded application).
You're using "aggregate initialization" but a class with a base class cannot be an aggregate, so you cannot use aggregate initialization.
As the comment above says, if you add a suitable constructor then you can use the same syntax:
struct bStruct : aStruct {
constexpr bStruct(int a, int b, int c) : aStruct{a, b}, c(c) { }
int c;
};
(You don't need a constructor for aStruct
because that is still an aggregate so can still be initialized directly using aggregate initialization).
You need to define a constructor in bStruct like this:
bStruct(int a, int b, int c) : aStruct{a, b}, c(c) {}
This will initialize aStruct and the c field.
Note: This is c++11 code.
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