0

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

Community
  • 1
  • 1
Erik
  • 11,944
  • 18
  • 87
  • 126
  • 4
    one returns reference, latter pointer, http://www.parashift.com/c++-faq-lite/references.html – Anycorn Oct 22 '10 at 15:22
  • @sbi this question seems different from that. This one seems like "What is the difference between pointing at a cake and eating it? I thought that is the same!" and the other one seems like "What should I do when I want a piece of cake from my friend? Ask him or just eat it away?". Nothing in the pointed to question (no pun intended) answers this question. I rather downvoted this one, because it's "Not A Real Question". What difference? The lexical one? "One uses & the other uses *". The syntactic one? "One uses a reference the other uses a pointer". The use-case of the two? – Johannes Schaub - litb Oct 22 '10 at 15:33
  • Thanks for your answer. so if I create a std::map this will insert references to the objects, not pointers, nor copy the objects itself, right? – Erik Oct 22 '10 at 15:39
  • std::map isnt correct, references are not copyable (there are other restrictions as well, read FAQ). – Anycorn Oct 22 '10 at 15:42
  • So I could make: std::map ? – Erik Oct 23 '10 at 09:23

2 Answers2

4

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
  • 30,295
  • 39
  • 137
  • 267
1

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
  • 37,467
  • 22
  • 115
  • 187