Pointers and References

http://quiz.geeksforgeeks.org/commonly-asked-c-interview-questions-set-1/

Reference

Definition: A reference is another name for a pre-existing object and it does not have memory of its own. (for efficiency gaining)
Syntax:

int x;
int& foo = x;
  • cannot be created without specifying where in memory it refers to.

Similarities

  • change local variables inside another function.
  • save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain.

Diferences

References are less powerful than pointers

  • Reference cannot be reseated.
  • References cannot be NULL.
  • Reference must be initialized when declared.
  • References in C++ cannot be used for implementing data structures like Linked List, Tree, etc.

References are safer and easier to use:

  • no wild reference as wild pointer.
  • easier to use: References can be used like normal variables. ‘&’ operator is needed only at the time of declaration.
  • access member of an object reference: '.' vs. '->'.

Notes

  int *p = new int;
  *p = 7;
  int *q = p;
  *p = 8;
  cout << *q << endl;
  // output 8

```

results matching ""

    No results matching ""