Recent Changes - Search:

Coding C++

Computing

References and Pointers

Trail Index | References and Pointers

This part still needs work...

References

The most basic definition of a reference variable is as an alias for another variable:

int a=2;   // true variable
int &r=a;  // reference - note the &
r=3;       // use it like a normal variable
cout<<a<<endl; // outputs 3 !

By far the most common use of references, anyway, is in parameter passing to functions. In this way, the function gets not a copy of the value, but the original variable in itself. This can be used

  1. to be able to modify the argument variable in the function, or
  2. to avoid a time and memory consuming copying operation.

The first kind of use is usually not good coding practice, and can usually be avoided by using more appropriate data structures. The second case is very common instead, and strongly suggested. You can usually tell the two apart because the first will use type& arg, but the second will use the safe const type& arg.

/**
 * Reference arguments
 */


#include <cmath>
#include <string>

/*
 * This function modifies its arguments, so that
 * This is something very far from the mathematical concept of function
 */

void rotatePoint(double& x, double& y, double angle) {
    double theta=atan(y/x);
    double r=sqrt(x*x+y*y);
    x=r*cos(theta+angle);
    y=r*sin(theta+angle);
}

/*
 * better to try to stick to "functional programming",
 * use objects and identify clearly the roles.
 */

class Point {
public:
    double x,y;
public:
    Point& rotate(double angle) {
        double theta=atan(y/x);
        double r=sqrt(x*x+y*y);
        x=r*cos(theta+angle);
        y=r*sin(theta+angle);
        return *this;
    }
};
/*
 * If you insist on a function, make it return an object
 */

Point rotatePoint(const Point& p, double angle) {
        Point p2=p;
        return p2.rotate(angle);
}

/**
 * But there can be valid reasons to use references,
 * like this swap subroutine.
 * (actually, you should use the one in the standard library..)
 */

void swapVariables(double& v1, double& v2) {
    double t=v2;
    v2=v1;
    v1=t;
}

/*
 * you should use const references to avoid
 * temporary copies of big chuncks of data
 * or complex classes:
 */

class MyVeryBigDataObject {
    int bigArray[1024*1024];
};
void doSomething(const MyVeryBigDataObject& obj) {}

/**
 * this includes strings, which can be big, and "expensive" to copy
 */

void printThis(const std::string& str) {}

int main() {}

Pointers

A pointer is similar to a reference:

int a=2;   // true variable
int *p=&a; // pointer to the memory address of a
*p=3;      // * "dereferences" the pointer
cout<<p<<endl; // outputs 0xBigExadecimalNumber
cout<<*p<<endl; // outputs 3

Like references, pointers can be used for parameter passing:

void f(const DataPoint* p) {
   ...
}
int main() {
    DataPoint d;
    f(&d);
}

The real difference from a reference, beyond the syntactic peculiarities of its usage, is that a pointer is not just an alias, but a variable in itself; a variable that contains a memory address:

int a=2;   // normal variable
int *p=&a; // pointer to the memory address of a
cout<<p<<endl; // outputs 0xBigExadecimalNumber !
int b=2;   // normal variable
p=&b;      // memory address of b
cout<<p<<endl; // outputs a different 0xBigExadecimalNumber !

Up to this point, there does not seem to be much reason for the existance of pointers, except for the fact that plain C libraries, which are often used from C++, usually require pointers for parameter passing, since C does not have references.

Note on C++, Java and C

It is interesting to note how the explicit use of references makes C++ more consistent than Java: in Java a function call passes arguments by value for "native types", and by reference for objects; but the syntax does not give any hint of this inconsistency - you just have to be aware of it. C++ instead consistently passes all parameters by value, and pass-by reference has to be explicitly requested in the declaration of the function.
What is not so evident instead, and somewhat disconcerting or even upsetting for a programmer used to plain C, is that calling a function with reference arguments is not distinguishable from calling a function with non-reference arguments. In plain C the equivalent of pass-by-reference can only be obtained with explicit passing of pointers, which is far more evident in the function call.

< Header Files | Trail Index | C Array >

Edit - History - Print - Recent Changes - Search
Page last modified on February 26, 2009, at 01:21 pm