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();