0

Consider the two cases:

  1. Object& obj = *getObjectPtr();
  2. Object obj = *getObjectPtr();

What is the difference between these two in C++?

Mathew Kurian
  • 5,949
  • 5
  • 46
  • 73

2 Answers2

4

Line (1) is semantically equivalent to Object *obj_p = getObjectPtr(), and then using *obj_p. The reference behaves like a pointer, but without pointer syntax. More examples here: http://en.wikipedia.org/wiki/Reference_%28C++%29

Line (2) will cause a new Object to be created, and the Object at the memory address getObjectPtr() to be copied into it via (probably) Object's copy constructor.

Andrey Mishchenko
  • 3,986
  • 2
  • 19
  • 37
1

Object& obj = *getObjectPtr(); - obj will hold a reference to the original object that is returned by getObjectPtr().

Object obj = *getObjectPtr(); - obj will hold a copy of the original object that is returned by getObjectPtr().

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Billie
  • 8,938
  • 12
  • 37
  • 67