In C++, is it good practice to initialize a variable by passing a reference to it into an "initialization" function? Or, to put it another way, it is good practice to write functions that behave this way (i.e. update variables created somewhere else)? In my intro programming class (taught in Java), we were taught to write methods like this as static
and to give them explicit return values. But I've noticed from looking at a few samples that some C++ programmers declare their variables with no explicit initialization, hand them off to some function, then proceed to use them in the program. Are there any advantages/drawbacks for either style? (I'm excluding purely OO stuff like member functions and variables from this question - this isn't just about using methods to update an object's state. I've seen this done outside of classes in C++).
I wrote a few quick lines of code to illustrate what I mean. The first function genName()
is the style I'm familiar with. The second, gen_name()
is the kind I'm curious about.
string genName() {
string s = "Jack" ;
return s ;
}
void gen_name(string & s) {
s = "Jill" ;
}
int main(int argc, const char * argv[]) {
string name1 = genName() ;
string name2 ;
gen_name(name2) ;
cout << name1 << endl ;
cout << name2 << endl ;
return 0;
}