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,838
  • 5
  • 43
  • 72

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,747
  • 1
  • 17
  • 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
  • 505,946
  • 29
  • 409
  • 696
Billie
  • 8,528
  • 12
  • 35
  • 64