Search code examples
c++referencec++-faq

What is a reference in C?


I have just started C++ and have come across references and have not understood completely.

References , as i read is an alternative name for an object.Why use that instead of directly accessing the object as any operation on references is directly reflected on the object ...?

  1. Why and when are they used ?
  2. Is ist like a constant pointer that is referenced each time it is used ... ?

And , it says

 double& dr = 1;  ----  says it is an error (some lavalue needed) 
 const double& cdr = 1;  ---- says it is ok. 

i dont understand it properly..So please explain why it is so ...

Thank You...:)


Solution

  • Why use that instead of directly accessing the object as any operation on references is directly reflected on the object ...?

    C++ passes parameters by value, meaning if you have a function such as:

    void foo(MyObject o) { ... }
    

    By default C++ will make a copy of a MyObject, not directly use the object being passed in. So, one use of references is to ensure you are working on the same object:

    void foo(MyObject &o) { ...}
    

    Or, if you aren't modifying o:

    void foo(const MyObject &o) { ... }