Reputation: 2595
I have a class Foo
where I need to initialize a reference to another class, but first I need to get some reference interfaces from another classes.
This is just a dummy code to explain a bit better my two questions:
class Foo
{
public:
Foo();
~Foo();
private:
int m_number;
OtherClass& m_foo;
};
Foo::Foo() :
m_number(10)
{
// I really need to do this get's
Class1& c1 = Singleton::getC1();
Class2& c2 = c1.getC2();
Class3& c3 = c2.getC3();
//How can I put the m_foo initialization in the initialization list?
m_foo(c3);
}
The questions are:
1 - I need to retrieve all those references above, before I initialize my member m_foo
. But I would like to initialize the m_foo
on the initialization list. What's the nicest way to accomplish that without having that in a single line.
Is there any way?
2 - By doing the code above, I get the error:
error: uninitialized reference member 'OtherClass::m_foo' [-fpermissive]
Because I'm initializing with the parentheses as it would be done in the initialization list. How can I initialize then the m_foo
properly?
Upvotes: 3
Views: 239
Reputation: 217085
You may use delegating constructors (since C++11):
class Foo
{
public:
Foo() : Foo(Singleton::getC1()) {}
private:
explicit Foo(Class1& c1) : Foo(c1, c1.getC2()) {}
Foo(Class1& c1, Class2& c2) : Foo(c1, c2, c2.getC3()) {}
Foo(Class1& c1, Class2& c2, Class3& c3) : m_number(10), m_foo(c3)
{
// other stuff with C1, c2, c3
}
// ...
};
Upvotes: 8