If I have a class Foo
and create an instance bar
, what does the &
mean in the following code?
Foo& bar = Foo();
If I have a class Foo
and create an instance bar
, what does the &
mean in the following code?
Foo& bar = Foo();
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.
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.