I understand passing a pointer, and returning a pointer:
char * strcat ( char * destination, const char * source );
You’re passing a variable that contains the address to a char; returning the same.
But what does it mean to pass something using the reference operator? Or to return it?
string& insert ( size_t pos1, const string& str );
I mean, I understand what actually happens, I just don’t understand the notation. Why isn’t the notation this instead:
string * insert ( size_t pos1, const string * str ); //made up
I presume it has something to do with passing/returning the instance of a class, but what? Is this syntax valid; if not why not and if so what does it mean?
char & strcat ( char & destination, const char & source ); //made up
(all of the function declarations, except the last made-up two, are from http://www.cplusplus.com )
Simply said, a reference is a pointer without telling you it’s a pointer.
If you would write the following in plain C:
You can write the following in C++ using references:
It has the additional advantage that you can move from normal by-value argument to by-reference argument, without making changes to the caller. Suppose you have this:
But after a while, class X becomes really big and you don’t want to pass it by value anymore.
In plain C you have to change the argument to a pointer argument, and change all the callers.
In C++ you can simply do this:
And you don’t have to change any of the callers.