You're really returning a reference, not passing it.
Anyway, it might cout the same thing, but it isn't the same thing. Just as a pass-by-reference can change the original's value, so can a return by reference:
Another way to say it, perhaps better, the first returns an int, the second returns m_space.
Returning a reference to a primitive data type isn't very useful. However, if you want to return an object, then you would want/need to return the reference as to not copy the contents of your object on the stack.
Sending a reference does not change the object. But you can change the object using the reference. Usually, you want to pass an object around and not actually copy it everywhere. There are situations where making a copy is necessary, but it seems to be a little less common where you need to.
I personally like to pass around pointers to my objects, instead of references, but I'd say that's just personal preference.
And if you don't pass by reference/pointer, you'll most likely need to write a copy constructor.
I just posted this in another thread but meh, it's a cool function and i like it :)
this is with vectors
string& name (vector<string>& list, int i); // function prototype
1 2 3 4 5 6 7 8 9 10 11
vector<string> list; // vector called list
list.push_back("bob");
list.push_back("monique");
list.push_back("victoria");
list.push_back("billy"); // populated..
for ( unsignedint i = 0; i < list.size(); i++ ){
cout<<name(list, i)<<endl; // displays the vector
}
string& chName = name(list, 1); // now chName is assigned to list[1];
1 2 3
string& name (vector<string>& vec, int i){
return vec[i]; // this is the function definition
}
edit: i should also have said, he asked the point, this is all i can think of cause i don't really know much about references, it makes vectors easer for me because im still learning. :)
for ( unsignedint i = 0; i < list.size(); i++ ){
cout<<list[i]<<endl; // displays the vector
}
Interesting discussion, don't have much to add.
Here's a way to access the memory address of a char array index: #define address(x) static_cast<const void*>x
Here's a little ditty:
1 2 3 4 5
char a[] = "A";
char *b = "B";
(&a == address(a)) // this is true
(&b == address(b)) // this is false
So? A reference to a char array is the mem address of the first index. A reference to a char * is not. The value in the char* is the address of the char array.