0

Suppose we have a class called Line that contains the following modifier that assigns a value to a class data member.

void Start(const Point &start);

The line class contains two data members called start and end which are both Point objects. Since the start variable in the function parameter is a reference, and I implement it as follows:

void Line::Start(const Point &start) { m_start = start; }

In the main function I have the following.

Line line; Point start(1, 1); line.Start(start);

Would the m_start data member now refer directly to the start Point object in the main function since it was passed by reference?

Mutating Algorithm
  • 2,604
  • 2
  • 29
  • 66
  • 3
    Where is the declaration of `m_start`? If `m_start` is a `Point` then no, the value is copied. If it is a const reference then you have a compile error. You need to initialize const members and references in the initializer list. – Retired Ninja Aug 12 '18 at 01:43
  • 1
    Have you made any attempt to test this yourself, such as changing the point after and having another class method which outputs data from the passed `Point` reference to see if it is the same `Point`? – Nick is tired Aug 12 '18 at 01:45

1 Answers1

2

Would the m_start data member now refer directly to the start Point object in the main function since it was passed by reference?

No. One of the properties of C++ references (and one of the ways in which their behavior differs from that of pointers) is that it's impossible to reseat a reference -- that is, you can't make a reference that was 'referring to' one thing later 'refer to' a different thing. (And of course if your m_start member variable was of type Point rather than type Point &, then there's no reference to attempt-to-reseat anyway)

Instead, start's copy-constructor will be invoked to copy start's contents into your m_start member-variable.

The upshot is that your Start() method will behave exactly like a similarly-implemented void Line::Start(Point start) method would, with the following exceptions:

  1. In your const Point & version of Start(), no separate/method-local copy of the Point object is made

  2. In your const Point & version of Start(), trying to modify start from within the method would be a compile-time error (whereas in the pass-by-value version, the code inside Start() could modify the argument, but the modifications would never be visible outside of the Start() function since they'd only modify the local variable/parameter)

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234