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
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
}
};
There's a couple of patterns to achieve this.
In C++11 use delegating constructors:
class Baz {
public:
Baz(Paramaters p) :
Baz{p, Something{p}}
{}
private:
Baz(Paramaters p, Something temp) :
f{p, temp},
b{p,temp}
{}
const Foo f;
const Bar b;
};
Use a base class:
class BazBase {
public:
BazBase(Paramaters p, Something temp) :
f{p, temp},
b{p,temp}
{}
protected:
const Foo f;
const Bar b;
};
class Baz : private BazBase {
public:
Baz(Paramaters p) :
BazBase{p, Something{p}}
{}
};
Use a factory method:
class Baz {
public:
static Baz make(Parameters p)
{
return {p, Something{p}};
}
private:
Baz(Paramaters p, Something temp) :
f{p, temp},
b{p,temp}
{}
const Foo f;
const Bar b;
};