2

I'm a beginner to C++ (coming from Java).

I'm trying to wrap my head around normal variables, pointers, and references. Normal variables I get. Pointers too. References confuse me a bit.

I think I understand the idea behind references: firstly, they are 'automatically dereferenced' pointers. Instead of having to do *pointer = something, pointer->doStuff() (which is syntactic sugar for (*pointer).doStuff()) and similar stuff, we can simply do reference = something, reference.doStuff(), etc.

Secondly, they are 'safer pointers', in that they can't be re-seated and you can't do arithmetic on them.

But there's one last thing I want to be sure about:

I'm pretty sure that where ever a reference variable appears in an expression or statement, it 'automatically' gets translated into the name of the variable it's referencing. So wherever I see the name of a reference, I can regard it as the name of the variable being referenced, and that would be correct.

Which means: you never operate on references, you always operate on the objects they reference. You can't store references, you always store the objects they reference. Etc.

Is this assumption accurate?

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131
  • 1
    You will get very complicated descriptions of references and why they are totally not pointers, but just imagine that references are pointers in disguise with some special restrictions (as you realize), and as you say you already understand pointers, you now understand references. – Neil Kirk Oct 08 '14 at 00:04
  • 1
    (Noting also that the thing they are referencing may not have come from a variable. It could have been an anonymous temporary, or from the heap.) – Raymond Chen Oct 08 '14 at 00:05
  • How to store a reference: `struct ref { ref(int& r) : r(r) {} int& r; }; vector tada_array_of_references;` – Neil Kirk Oct 08 '14 at 00:06
  • You seem like you've mostly got the right idea but it's not quite true to say you can't store references. Classes can have references as members and in that case you really are storing the reference not the referenced object, just as if you had a pointer member. – mattnewport Oct 08 '14 at 00:06
  • References across functions calls should be implemented via pointers; references within the same scope should be "instantly translated to the object", as you say. – Petr Skocik Oct 08 '14 at 00:09
  • @PSkocik Your comment is a bit ambiguous. I get what you mean, but it sounds like you could be advising against passing references to functions as parameters. – Neil Kirk Oct 08 '14 at 00:10
  • @NeilKirk Btw, say I have a function `void func(Thing t)`. I'm calling it like so: `func(referenceToSomething);`. This gets implicitly translated to `func(something);`, right? – Aviv Cohn Oct 08 '14 at 11:40
  • @AvivCohn It's the same as `Thing *ptrToSomething = ..; func(*ptrToSomething);` – Neil Kirk Oct 08 '14 at 14:27

0 Answers0