0

If I have the classes Register and Line, where each Register object will include a reference to a Line object, how can I write it?

 class Register{ public: Line &line; Register(Line &object){ line = object; } }; 

is this valid? If not what can I do? Thank You.

5
  • "is this valid?" - Would you really be asking if it was working? Commented Dec 10, 2017 at 20:40
  • @StoryTeller yes, but I read that references have to be initialized, but am I not assigning? So I don't know if it would work. Commented Dec 10, 2017 at 20:42
  • You have to make sure that the Line object referenced in your Register class outlives the Register object, otherwise you will run into trouble. Commented Dec 10, 2017 at 20:49
  • A reference member is almost never what you want. You won't be able to copy a Register, and you need to be very careful about lifetimes. Commented Dec 10, 2017 at 20:51
  • You are assigning. Assignment and initialization are different. Commented Dec 10, 2017 at 20:53

1 Answer 1

1

Reference members must be initialized in the ctor initializer list, assigning to them in the ctor body is not the same thing at all:

class Register { public: Line & line; Register(Line &object) :line(object) {} }; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.