In C++, is there any way to have something like a temporary variable in an initialization list. I want to initialize two constant members with the same instance of something without having to pass that something in, remove the const requirement, use a Factory (i.e. pass it in but have the factory generate it to hide it from the API user), or have temp actually be a member variable.
I.e. something like
Class Baz{
const Foo f;
const Bar b;
Baz(Paramaters p):temp(p),f(p,temp),b(p,temp){ //temp is an instance of Something
// But NOT A member of Baz
// Whatever
}
}
instead of
Class Baz{
Foo f;
Bar b;
Baz(Paramaters p){
Something temp(p);
f = Foo(p,temp)
b = Bar(p,temp)
}
}
or
Class Baz{
Foo f;
Bar b;
Baz(Paramaters p,Something s):f(p,s),b(p,s){
}
}
In C++11 you could use delegating constructors:
class Baz{
const Foo f;
const Bar b;
Baz(Paramaters p) : Baz(p, temp(p)) { } // Delegates to a private constructor
// that also accepts a Something
private:
Baz(Paramaters p, Something const& temp): f(p,temp), b(p,temp) {
// Whatever
}
};
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