[snip] I would like to
do some caching of calculated result, which I then use to pass to the
base's constructor, and will use further in the object's lifetime for
other purposes. Normally I would store the result in a variable, and
not initialize any members, but given the limited syntax of
initializer lists, I cannot implement logic that I would do normal
code. Let me clarify with another example:
struct Base
{
Base(int v) {...};
}
struct Derived: public Base
{
int d;
void veryCostlyCalculation()
{
....
d = <calculation result>
}
Derived()
:veryCostlyCalculation(), Base(d) {}
};
In an initialization list, how can I store the result of
veryCostlyCalculation() in a local variable, so that I don't use
members?
This works but isn't pretty:
#include <iostream>
struct Base
{
Base(int v) : dBase(v) { }
int dBase;
};
struct Derived : public Base
{
Derived(int cachedValue = 0) :
Base(cachedValue = veryCostlyCalculation()),
dDerived(cachedValue)
{
}
static int veryCostlyCalculation()
{
std::cout << "veryCostlyCalculation\n";
return 12;
}
int dDerived;
};
int main()
{
Derived d;
std::cout << d.dBase << "\n";
std::cout << d.dDerived << "\n";
}