I have the following class:
//in some .h file
#define BARS_IN_FOO 5 //The only place where this number should be specified.
//All code should work when I change this
//in some .cpp file
struct Foo;
struct Bar { Foo & foo; Bar(Foo & foo) : foo{ foo } {} } //Cannot be default initialized
struct Foo {
std::array<Bar, BARS_IN_FOO> myBars;
Foo() :
myBars{ } //Error. Cannot default initialize Bars.
//I want to initialize all Bars with Bar{*this} but at this point I don't
//know how many Bar initializers I should put in the myBar initializer list
{}
}
So how should I initialize Foo::myBars? The number of Bars is known at compile time but I just want to specify this number in one place (in the define preferably, other suggestions are welcome).
Usage of Foo::mybars:
- Size of it will never change during runtime but I haven't decided what the number will be yet but will be somewhere in the range [1..10] (or so) (number might change a lot during development).
- Element values will never change (always will be the same non-const objects).
- Relation ship between
FooandBaris that of composition. AFoois made out ofBars and their lifetime is the same.Barwithout aFooand visa versa makes no sense. - The
FooandBarclasses are part of performance critical code and their size will influence the memory footprint of the program a lot (80-90% of the memory footprint will beFoos andBars).
Compiler: MSVS2017 version 15.3
Edit: Changing std::array<Bar, BARS_IN_FOO> myBars; to Bar myBars[BARS_IN_FOO]; is also oke if this helps.
Important edit: All the ctors of Bar and Foo are public. This was a mistake. I changed this.
#defineis a red herring, the real problem is thatBarhas no default constructorBarwithout its containingFooinstance also makes no sense. Of course I can always changeBar::Foo&intoBar::Foo*and create the link at a later time (that is, in the body ofFoo::Foo()after the initializer list) but I want to explore other options first.Fooconsists ofBars and aBarknows its parentFoo.Foowith an array ofBarswhich each have a reference to thatFoo.