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:
ExampleClass* doSomething(ExampleClass* ec) {
return ec;
}
ExampleClass * pointer = new ExampleClass();
ExampleClass * anotherpointer = doSomething(pointer);
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:
ExampleClass* doSomething(ExampleClass& ec) {
return &ec; // & unary operator - get the address of ec
}
ExampleClass obj = ExampleClass();
ExampleClass* pointer = doSomething(obj); // it will automatically get a reference to the input object
The next example takes a pointer and returns a reference instead (notice that the return type is not a pointer):
ExampleClass& doSomething(ExampleClass* ec) {
// note ec of is type ExampleClass*
// *ec is of type ExampleClass
return *ec; // returns a reference to whatever the pointer points to
}
ExampleClass * pointer = new ExampleClass();
ExampleClass& myobj = doSomething(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:
ExampleClass& doSomething(ExampleClass& ec) {}
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:
ExampleClass& doSomething(ExampleClass* ec) {
ExampleClass copy = *ec;
return copy; // WARNING: returning reference to object that will be destroyed
}