Results 1 to 2 of 2

Thread: C++: Pointers vs. References

  1. #1
    Join Date
    May 2007
    Location
    USA
    Posts
    373
    Thanks
    2
    Thanked 4 Times in 4 Posts

    Default C++: Pointers vs. References

    To make things clear, is the difference between pointers and references in C++ simply that:

    references are just aliases for another variable, in that the original var and the ref have the same address

    whereas pointers are data types that contain information about an address (where an object/primitive is located in memory), but multiple pointers to the same object do not necessarily have the same address for themselves?

    (I come from a Java and JavaScript background.)
    Last edited by Trinithis; 09-05-2007 at 06:14 AM.
    Trinithis

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Different references have different memory addresses too. The main difference between a pointer and a reference is that a reference can only ever point to the object you originally assign it. Pointers can be manipulated, but references can't. References are mainly a convenience: they simplify uses of pointers where you're never going to need to change the pointer itself. For example,
    Code:
    void addOne(int *n) {
      *n = *n + 1;
    }
    
    // ...
    
    int myint = 3;
    addOne(&myint);
    ... can more simply be written as:
    Code:
    void addOne(int &n) {
      n = n + 1;
    }
    
    // ...
    
    int myint = 3;
    addOne(myint);
    You see how the use of a reference rather than a pointer makes everything pretty much transparent; the only difference from passing by value is the & symbol.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •