No, you'd be making a copy!
m_pos
is a
Transform
, not a
Transform&
.
If you want to store a reference, you need to change the declaration of
m_pos
to be (line 7)
Transform &m_pos;
, but that's not all. Since references
cannot be null, i.e., they always refer to a real object, they have to be initialized with a value.
Member objects and some other stuff is initialized before the code making up the constructor body is run. The constructor body is the stuff on line 4 of your example above. If you need to do something other than "default initialize" a member, you need to do so in the constructor initializer list.
The syntax looks like this:
1 2 3 4 5 6 7 8 9
|
class Character {
public:
Character(const Transform &position)
: m_pos(position) {
/* You don't need to do anything here: `m_pos' now refers to `position' */
}
private:
Transform &m_pos;
};
|
This problem is similar to what happens if you take your snippet above but mark
m_pos
const
. You can't just assign to a constant value, but you can initialize it: this is the difference between calling an assignment operator in the constructor (m_pos = position) and actually initializing the value when it's constructed.
In other words, the difference is like that between
int const foo = 5;
or
int &baz = some_int;
and
int const foo; foo = 5; /*oops! doesn't compile!*/
or
int &baz; /*oops! doesn't compile!*/ baz=some_int;
.
Edit:
Make sure the referred-to value exists the next time you use it. Once m_pos is initialized, nothing stops it from being destroyed and leaving this class with a "dangling reference".
The issue is that this class doesn't control the lifetime (doesn't "own") the value to which
m_pos
refers. Now it's the caller's problem to make sure that the referred-to value still exists.
At some point you should look into "smart pointers", which help enforce those ownership semantics and make things easier in general.