Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 204
lital maatuk Avatar asked Oct 23 '25 16:10

lital maatuk


2 Answers

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.

like image 84
Sasha Goldshtein Avatar answered Oct 26 '25 07:10

Sasha Goldshtein


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.

like image 36
Bo Persson Avatar answered Oct 26 '25 06:10

Bo Persson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!