Thread: pass by reference versus by copy

  1. #1

    pass by reference versus by copy

    Hello all,

    I am new to C++, and have a quick ?, I am having trouble understanding what is the diffrence between pass by reference and pass by copy??

    I've read pass by reference is better as it'll make a copy of the parameter so that the orginal will not be altered, but by copy will allow the the original to be altered?? it this correct?? I'm just not getting this concept?? could someone please explain, I really new to C++ so want to make sure I completely understand all the basic concepts.....

    also, by reference: int function (int &parameter)?? is this correct with the &....

    many thanks

  2. #2
    When you pass by reference, it is as if you are passing the variable directly.

    This is how functions work: when you pass a variable to one, it makes a local copy. Thus when you change that variable in the function, the variable from main, or wherever, that you passed to the function, is not altered. When you pass by reference, the altering the function variable (the reference) alters the variable that is referenced, the variable passed to the function. There is also the pointer way, where you pass the address of a variable and indirectly access the variable in the func. The following two pieces of code change the value of x, the last version does not:

    void dostuff_ptr(int*);
    void dostuff_ref(int&);
    void dostuff(int);

    int main (void)
    int x = 5;
    dostuff_ptr (&x); // x is now equal to 7
    dostuff_ref (x); // x is now equal to 9
    dostuff (x); // x is still 9
    return (0);

    void dostuff_ptr (int *a)
    *a = *a + 2;

    void dostuff_ref (int & a)
    a = a + 2;

    void dostuff (int a)
    a = a + 2;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. is it possible to pass a structure element by reference?
    By Cathalo in forum C++ Programming
    Replies: 6
    Last Post: 03-04-2009, 10:01 AM
  3. Pass by reference
    By jrice528 in forum C++ Programming
    Replies: 4
    Last Post: 10-30-2007, 01:02 PM
  4. C OpenGL Compiler Error?
    By Matt3000 in forum C Programming
    Replies: 12
    Last Post: 07-07-2006, 04:42 PM
  5. GCC - Strange networking functions error.
    By maththeorylvr in forum Windows Programming
    Replies: 3
    Last Post: 04-05-2005, 12:00 AM