0

I saw this example in an answer here on stackoverflow regarding returning this in a c++ function return “this” in C++?, where the question was how to handle returns of this is handled in c++. The best answer said that

class myclass {
  public:
  // Return by pointer needs const and non-const versions
     myclass* ReturnPointerToCurrentObject() { return this; }
     const myclass* ReturnPointerToCurrentObject() const { return this; }

  // Return by reference needs const and non-const versions
     myclass& ReturnReferenceToCurrentObject() { return *this; }
     const myclass& ReturnReferenceToCurrentObject() const { return *this; }

  // Return by value only needs one version.
     myclass ReturnCopyOfCurrentObject() const { return *this; }
};

Now I dont understand how

myclass& ReturnReferenceToCurrentObject() { return *this; }

cannot be the same as

myclass ReturnCopyOfCurrentObject() const { return *this; }

As I see it the first example returns a reference and the second returns a dereferenced pointer (value)? How can these two functions have the same function body?

Community
  • 1
  • 1
patriques
  • 5,057
  • 8
  • 38
  • 48
  • 2
    Given `int* p`, do you understand that `int x = *p` and `int& x = *p` are also both allowed? The first one does a copy. `myclass` is no different; it will perform a copy. – Simple Mar 10 '14 at 11:53
  • 1
    It is a matter of syntax. There is no "make reference" operator analog to "take address of" operator in C++. References are designed to appear as if they were object itself. – Ivan Aksamentov - Drop Mar 10 '14 at 11:55

2 Answers2

3

As I see it the first example returns a reference and the second returns a dereferenced pointer (value)?

Exactly. The first returns a reference to the object it's called on; the second returns a copy of that object.

How can these two functions have the same function body?

Because the conversion from the return expression *this to the return value is implicit. In the first case, it's converted to a reference; in the second, it's converted to a value by copying it.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

To understand the difference it will be helpful to consider a more simple example. Let;s assume that there are two stand-alone functions

int f()
{
   static int x;
   return x;
}

int & g()
{
   static int x;
   return x;
}

As you see the both functions have the same body and return statements.

The difference between them is that in the first case a copy of static variable x is returned while in the second case a reference to static variable x is returned.

So in the second case you can do for example the following

g() = 10;

and variable x defined in the body of the function will be changed.

In the first case you may not and can not do the same. In this case a temporary int object is created that is a copy of variable x.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335