0

Essentially, what's the difference between:

const Date& default_date()
{
    static Date dd(2001,Date::Jan,1);
    return dd;
}

and

const Date default_date()
{
    static Date dd(2001,Date::Jan,1);
    return dd;
}

Does the function signature really matter? I don't think of Date& as a type like *Date, so I'm not sure what difference this makes. Does it just prevent a copy from being made on the return? But then wouldn't you return &dd?

Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
CDC
  • 51
  • 5
  • Sounds like this will help you: http://stackoverflow.com/questions/57483/what-are-the-differences-between-pointer-variable-and-reference-variable-in-c – chris Sep 20 '12 at 05:15
  • const or not, i would never use the & operator to return anything from inside a ?function? If you something outside allocate it otherwise somebody in a large code base will eventually remove the const and your application ends up with terrible segvaults – Oliver Sep 20 '12 at 05:25
  • Question heading is bit confusing, Returning object vs. reference in **default constructor signature**, IMO **bold** part should removed. – MarsRover Sep 20 '12 at 06:11

1 Answers1

3

The first function returns a const reference to the static object, so you can do this:

const Date& d = default_date(); // d is a reference to the original

or

Date d = default_date(); // d is a copy of the original, 
                         // provided there is a copy constructor

The second one makes a copy of the static Date object, so you can only get a copy

Date d = default_date(); // d is a copy of the original

Returning &dd would return the address of the static object, which could then be assigned to a pointer to Date. The syntax for the return statement is the same for return by reference or return by value. The semantics depend on the return type of the function.

Note that in C++, functions such as default_date are not referred to as constructors.

Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • In the former, i think you're missing an '=' sign, as that doesn't compile as-is. In the latter, there is no provisional condition of a copy constructor, as without one (default or otherwise) the code will not compile either. the rest I'm totally behind (and up-voted). – WhozCraig Sep 20 '12 at 05:22
  • @CraigNelson thanks, someone else fixed the mistake. I haven't added the explicit condition of a copy constructor for the latter example because the function itself wouldn't compile without it. – juanchopanza Sep 20 '12 at 05:52