1

I am sure this question has been asked before. But I cannot seem to find the exact answer that I am looking for. Basically I am trying to create an object of the class as a member of the other class and pass one of the members by reference to the owned object through the constructor. Sometimes this seems to work, other times I get a random value.

I think that I am not understanding some rudimentary rule of initialization order

Here is the code example:

class Foo
{
public:
    Foo();
private:
    int b;
    Bar c;
};

class Bar
{
public:
    Bar(int& parm);
private:
    int& b_ref;
};

Foo::Foo(): b(0), c(b)
{}

Bar::Bar(int& parm): b_ref(parm)
{}

What I want is for c to own a reference to b and be able see the value as it changes.

Should I not use the initialization list in this case?

1 Answer 1

3

The rule is that objects are initialised in the order of their declaration in the class. In this case, it means that b is initialised before c, so this code should always work correctly.

If you swapped the order of the b and c members, then the int referenced by param would not yet be initialised in the constructor of Bar.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes I just realized that my actual code had the members swapped! Thank you that was exactly the problem.

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.