Pointers to Objects

Suppose we have a class counter with a member function

        void increment();
And then we declare the following:
	counter *bozo = new counter;
So bozo now is a pointer to a counter, and *bozo is a counter. How would we invoke the member function increment? How about
	*bozo.increment(); ???
This would not be correct. The "." operator has a higher precedence than the "*" operator, so the compiler would interpret it as
        *(bozo.increment());
That's not at all what we want, and the compiler would complain. After all, bozo is not an object, it's a pointer to an object, so we can't invoke a member function. And increment doesn't return a pointer (in fact, because it's void, it doesn't return anything), so we certainly can't dereference what increment returns. So we would have to use parentheses to get the interpretation that we want. This would then be
	(*bozo).increment(); //This would be ok
There exists a "syntactic sugar" form for this construct, and it involves a new operator. It is the "arrow" operator and is formed by a "-" followed immediately by a ">". To invoke the member function increment() using the arrow operator we would write
	bozo->increment();

See Demo ptrNotation.cpp

In general, ",code>x ->" is the same as "(*x)." whenever x is a pointer to an object. We can use "->" to access any members, whether they be functions or data of the object that x points to.

Arrays of Pointers to Objects

What if the drop objects in the raindrops program were big? That is to say, what if we needed a lot of memory to store one drop object? An array full of them could use a lot of storage. So what is the solution? We can make an array be of pointer to drop, i.e., each element is a pointer to a drop object rather than a drop object, and allocate space only as it is needed.

See Demo RaindropsPtr.cpp

We can make the above implementation of drops even more space-efficient by deleting drops once they are too big to draw.

See Demo RaindropsPtr2.cpp

Pointer to Pointers

It is important to remember that every "*" means to dereference.

See Demo ptrToPtr.cpp

A pointer to a pointer in the above demo looks like

So now what? Well, now we can have dynamic multidimensional arrays.

Multi-dimensional Arrays

Suppose we want an M x N array, but we do not know M or N at compile time. This means that we cannot do the following

	int A[M][N];      //Cannot do!!!
Instead, we want something else. Something really cool!!! Graphically it looks like this:
What is the type of A? Notice that if we follow two pointers from it, we get an int. So A is a pointer to a pointer to an int. Hence, we would declare A as
      int **A;
Is this declaration of A consistent with wanting A[i][j] to be an int?

See Demo 2D-array.cpp

To Index Previous Next