Tuesday, May 4, 2010

From C to C++

reference: In C you can pass/return values to a function in 2 ways. 1. By value 2. By address (Using pointer). C++ introduces third way to return/pass values. It is called by reference. Reference is similar to a pointer but has following properties.
  • One variable can have multiple references
  • But a reference can refer to only one variable in its life time.
  • Reference needs to be initialized (declared and defined in same line).
    • You can't do int i; int &ref; ref = i;
    • int i; int &ref = i;
  • Reference are so tightly coupled that any change in one reflect in change in all others

Example:
int i = 10;
int &ref = i;

void funct_r(int &ref);
void funct_v(int val);
void funct_a(int *add);
...
...
main() {
int i = 10;
funct_r(i); // call by reference
funct_v(i); // call by value
funct_a(&i);
}

reference are more readable than pointers while for most part they work like pointers. Btw, it is also possible to create reference to a pointer.

e.g.
char *name = "India";
char *& ref = name; // Read from right to left... it says reference to a char *

Points to remember:
  • We cannot have a array of references
  • Never return local variable by reference

No comments:

Post a Comment