Thursday, April 24, 2008

Using pointers or using references?

What is the reason for using pointers if you can use references to get the same job done with less code. and wouldn't less code mean faster runtime of the program, i'm pretty sure that 4 or 5 lines wouldn't make that much of a difference but i'm just curious. and if there is a reasonable use for pointers, when do you decide if you need to use a pointer or a reference?

First we define a simple class
class A
{
public;
A(int x){m_a = x;}
int m_a;
};

Now for a couple of functions..

void by_ref_func(A & a)
{
a.m_a *= 2; //easy to read;
}

void by_ptr_func(A *pa)
{
pa->m_a *= 2; // not so intuitive
}


In main..
int main()
{
A a(5);
by_ref_func(a); //simple function

A *pa = &a //not so simple
by_ptr_func(pa);
return 0;
}
Three reasons to use pointers instead of references:
1. You need to access someone else's functions that require pointers in the parameter list -- most Win322 API functions are like that.

2. You are writing a library of functions that can be called from other languages, such as C, C++, Visual Basic, etc. You will have to make the parameters available to all these languages so the pointer is the only suitable parameter type.

3. You need to interate through a string for some reason -- pointers are more useful here than references. I frankly don't know how this could be done with a reference. For example:
int foo(char buffer[])
{
char *ptr = buffer;
while(*ptr != 0)
{
// do something with the character at the current pointer location
//
// point to the next character
ptr++;
}
}

The reference is a pointer on low level, so the code runs in the same way
as the code with pointers. It will have the same speed and size.

Basically, you need pointers to scan the arrays, as mentioned above. Also,
when you have a collection of polymorphic objects - they can only be the
created with new operator and therefore you keep array (or list) of pointers
to the base class.

No comments: