Mutating Algorithm
Mutating Algorithm

Reputation: 2758

Passing a const reference as a function parameter in a class member function

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?

Upvotes: 0

Views: 2917

Answers (1)

Jeremy Friesner
Jeremy Friesner

Reputation: 73364

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)

Upvotes: 2

Related Questions