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.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo