I’ve read a quick tutorial aimed for Java developers who want to learn C++. It only explained the basic principles (and syntax) of C++ (I guess). At first I thought, that I had understand everything completely, but while programming C++ something came up that’s not really clear to me.
Whats the difference between …
ExampleClass* doSomething(ExampleClass* ec) {}
and
ExampleClass* doSomething(ExampleClass& ec) {}
and
ExampleClass& doSomething(ExampleClass* ec) {}
and
ExampleClass& doSomething(ExampleClass& ec) {}
?
Pointers and references have similarities. They both point to or reference an object without having space to represent the object value themselves. The pointer however, explicitly uses the
*to dereference (as an unary operator), and&to get the address of an object. The*is also used in a different context, to specify a pointer type.The reference is a somewhat safer “automatic” pointer. A reference however is immutable in the sense that it cannot be later changed to point to something else. A reference also uses the
&symbol, but in a different context. Instead of being an unary operator, it is used to specify a reference type.The 1st example takes a pointer to an ExampleClass and returns a pointer to an ExampleClass object. Eg. you might say:
In contrast, this following takes a reference to ExampleClass instead. A reference is like a pointer, but it means you don’t pass something of pointer type, just pass it straight through, eg:
The next example takes a pointer and returns a reference instead (notice that the return type is not a pointer):
You just pass it to a reference object (which points to the object given by the function, ie. doees not make a copy). Note that in this case, the function should take care of making sure there is space allocated for the object, and does not need to explicitly reference (with *) the object in the return statement.
I think you can work out the last example:
Do note that when returning a reference, you must ensure that the object that is referenced is allocated space outside of the context of a function (eg. as a global, or static local variable), so that it is not destroyed.
You should not return a reference to a local variable, which will be destroyed when the function exits, eg: