tags:

views:

61

answers:

2

Possible Duplicate:
What is the proper way to return an object from a C++ function ?

Hi there,

i would like to know whats the difference between the following two functions with respect to the return types?

  1. MyClass& func1(void)
  2. MyClass* func2(void)

I always thought this would be the same?

Heinrich

+1  A: 

the first one returns reference to an object (or its address). The other one returns pointer, not reference

Major difference: the second one can return NULL

Kiril Kirov
Another major one, the second one can return a pointer into an entire array of objects.
UncleBens
You can also return a null reference, but that is quite ugly.
Benoit Thiery
There's no such thing.. NULL reference.. you could return 0x00,which is address zero,but it's not NULL ref.
Kiril Kirov
+1  A: 

The first one is only capable of returning a reference to a single object and may not be null. Or rather, it should not be null.

The second one may be returning the pointer to a single object, or an array of objects.

In cases where you wish to return a single object that cannot be null, #1 tends to be the preferred form. In cases where a null can be returned #2 has to be used. Some APIs don't return references at all (like QT).

This is strictly a syntactic difference however. These two types are handled exactly the same in the compiled code: a pointer to the object (or array) will be used. That is, strictly speaking, the reference notation & adds no new semantic functionality over a normal pointer.

(This perhaps just summarizes what the other people wrote)

edA-qa mort-ora-y
Good summary, thanks!
Heinrich