Wednesday, June 20, 2007

C++ Pointers VS JAVA Refrences

Here are some of the differences i found while googling.
  • Java references are closer to C++ pointers than to C++ references. Adifference between Java references and C++ pointers is that you can perform arithmetric operations on C++ pointers while you can't do arithmetic operations on Java references.
    In C/C++ e.g.:
int* a = new int[10];
int* b = a + 1;
int* c = b - 1;

*b = 2; // Modifies a[1]
*c = 1; // Modifies a[0]
  • A pointer is an object containing the address in memory of another Object while reference is an alias for another object.
  • A pointer can be re-seated (i.e., pointed at a different object); a
    reference cannot.
  • A reference must be initialized when it is created; a pointer can be uninitialized.
  • References "refer" to some object, and are "bound" to an object during creation, and are used as aliases to that object. Because references are aliases, the "contents" of a reference is actually the contents of the object they are bound to. Pointers "point" to an object. The "contents" of a pointer is the address of an Object. Pointers are not "bound" to any object; rather, they simply "point" to an object. The value of a pointer can be changed during its lifetime, causing it to "point" to different objects at different times. References are "bound" to an object, and it cannot be rebound during its lifetime.
  • "use references when you can, use pointers when you must."

No comments: