Initializing References and Variables In C++ -
given following c++ function:
int& returnareference() { /* here */ }
is there difference between 2 statements:
int normalvariable = returnareference(); int& referencevariable = returnareferene();
is 1 version preferred on other?
regarding this:
int normalvariable = returnareference();
normalvariable
integer, , assigned value of int returnareference()
references. such incrementing, assigning, or doing else normalvariable
not affect whatever returnareference()
has internally.
regarding this:
int& referencevariable = returnareference();
referencevariable
reference integer otherwise internal returnareference()
. such incrementing, assigning, or doing else referencevariable
will affect whatever returnareference()
has internally.
what preferred depends on you're trying accomplish, in many cases second approach (using referencevariable
) violates "encapsulation" ( http://en.wikipedia.org/wiki/encapsulation_(object-oriented_programming) ), considered poor design.
edit: , should add if returnareference() returning reference variable local in function, reference invalid returnareference() returns.