3

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?

4
  • Does c1, c2 and c3 get used for anything else? Commented Sep 15, 2015 at 19:48
  • 1
    @NathanOliver: I think the OP was pretty clear about this: Yes! "I really need to do this get's" Commented Sep 15, 2015 at 19:50
  • 1
    @Waggili Where? All he states is he needs them before he initializes m_foo Commented Sep 15, 2015 at 19:51
  • 1
    @waas1919 you're talking about member initializer lists not initializer_lists, I'd suggest modifying your title to make that clear. Commented Sep 15, 2015 at 19:57

1 Answer 1

8

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
    }
    // ...
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.