-4

If I have a class Foo and create an instance bar, what does the & mean in the following code?

Foo& bar = Foo();
Karnivaurus
  • 22,823
  • 57
  • 147
  • 247
  • just fyi, this would cause a compilation error because you're trying to initialize a reference with an rvalue – PeterT Dec 10 '14 at 15:52
  • 2
    In the code you show it means [*undefined behavior*](http://en.wikipedia.org/wiki/Undefined_behavior), ***if it even compiled***. If it was allowed by the compiler, the reason would be that `Foo()` creates a *temporary* object, and then you have `bar` as a reference to that temporary object. And as soon as the temporary object is destructed, which is basically immediately, you have a stray reference to something that doesn't exist anymore. – Some programmer dude Dec 10 '14 at 15:52
  • 1
    @JoachimPileborg It's only UB because the standard doesn't say what happens if you bind an object to a non-const reference. In the case of a const reference (`Foo const & bar = Foo();`) then the behavior is actually well-defined, and the lifetime of the temporary is extended to match the lifetime of the reference. – cdhowie Dec 10 '14 at 15:59

2 Answers2

0

Foo& bar means bar is reference to Foo object. However, I think compiler would shout for this line as temporary can not be bound to non-const reference.

ravi
  • 10,994
  • 1
  • 18
  • 36
0

It makes bar a reference to the right hand side instead of a copy of it.

C++ classes and structs are, by default, passed around by value, meaning they are copied on assignment. If you want to use them by reference, you use the & thing or pointers (with *) instead. You often want pointers for polymorphism too.

Adam D. Ruppe
  • 25,382
  • 4
  • 41
  • 60