lital maatuk
lital maatuk

Reputation: 6249

member variable as a reference

What is the advantage of declaring a member variable as a reference? I saw people doing that, and can't understand why.

Upvotes: 4

Views: 6229

Answers (3)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136306

Generally speaking, types with unusual assignment semantics like std::auto_ptr<> and C++ references make it easier to shoot yourself in the foot (or to shoot off the whole leg).

When a reference is used as a member that means that the compiler generated operator= does a very surprising thing by assigning to the object referenced instead of reassigning the reference because references can not be reassigned to refer to another object. In other words, having a reference member most of the time makes the class non-assignable.

One can avoid this surprising behaviour by using plain pointers.

Upvotes: 2

Bo Persson
Bo Persson

Reputation: 92271

A member reference is useful when you need to have access to another object, without copying it.

Unlike a pointer, a reference cannot be changed (accidentally) so it always refers to the same object.

Upvotes: 2

Sasha Goldshtein
Sasha Goldshtein

Reputation: 3519

One useful case is when you don't have access to the constructor of that object, yet don't want to work with indirection through a pointer. For example, if a class A does not have a public constructor and your class wants to accept an A instance in its constructor, you would want to store a A&. This also guarantees that the reference is initialized.

Upvotes: 5

Related Questions