0

What is the difference between returning by pointer and returning by reference? In both cases, the address is returned to the caller, am I right?

According to this little program - its obviously the same - it prints the value of an integer.

Are the any limitations concerning returning by reference rather than returning by pointer? My teacher tells us - when you return by reference to a receiver, the receiver "borrows" the object. When you on the other hand return a pointer - you "transfer" the ownership of the object to the receiver.

#include <iostream>
using namespace std;

class A {
    int x;

  public:
    A() : x(10) { }

    void print() {
        cout << "x = : " << x << endl;
    }

};

class B {
    int y;

  public:
    B() : y(30) { }

    void print() {
        cout << "x = : " << y << endl;
    }

    A& create() {
        A* a = new A;
        return *a;
    }
};

Return by pointer, then these parts of the code I changed:

A* create() {
   A* a = new A;
   return a;
}

And in the main:

 b.create()->print();
Mat
  • 202,337
  • 40
  • 393
  • 406
user2991252
  • 760
  • 2
  • 11
  • 28

2 Answers2

3

When you return a reference, you make an alias way to access to the object. It's like you are accessing the object directly.

By returning a pointer, you copy (not transfer) the address of the object. Then you need deferenece the pointer to access the object.

I think you can take a look at smart pointers such as std::unique_ptr and std::shared_ptr to understand transfering the ownership.

masoud
  • 55,379
  • 16
  • 141
  • 208
0

References are always treated as alias to original object, so no separate memory allocated to reference. Where as pointer has a separate memory address and store address of object.

user3607571
  • 126
  • 2
  • "no separate memory allocated" - references are implemented using pointers by many popular compilers. So this is not really true. But you're right semantically: I can never take the address of a reference, whereas I can take a pointer's address. – lethal-guitar May 06 '14 at 09:59