Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static initialization for structs extending structs

Tags:

c++

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).

like image 669
Brad Avatar asked Jun 30 '15 19:06

Brad


2 Answers

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).

like image 143
Jonathan Wakely Avatar answered Nov 13 '22 15:11

Jonathan Wakely


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.

like image 23
user5066801 Avatar answered Nov 13 '22 15:11

user5066801