"Scott" <sc***@nospam.com> wrote in message
news:pa****************************@nospam.com...
Hello,
I am having some difficulty with the following C++:
I have a declared a pointer to Foo like so:
Foo *pFoo;
Now, I have an API object that I try to use like so:
fooAPI.processFoo( pFoo );
Then, I get a compiler error that the prototype for processFoo is
expecting a Foo&, but is instead getting a Foo*&. So, my question is: how
do I transform my *pFoo to a Foo&, and perhaps someone could also help me
understand exactly what the difference between the two is? I hope this is
a least somewhat clear.
A reference works *sort of* like a pointer, but without the pointer syntax.
However, unlike a pointer, a reference must always refer to an object
(pointers can be NULL, references cannot), so for example, it is illegal to
write:
int & ref; // illegal -- 'ref' does not refer to anything.
Instead, you would have to write:
int i;
int & ref = i;
In this case, 'ref' refers to 'i' and for all intents and purposes 'i' and
'ref' are the same variable, representing the same space in memory, and both
may be used in the same ways. Thus, when writing:
ref = 6;
i = 6;
....both assignments above accomplish the exact same thing, that is,
assigning the value 6 to the variable 'i'.
Now, to your main question...since 'processFoo' expects a reference to a
'Foo' (Foo&), you cannot pass it a pointer, so you must dereference the
pointer so that the function gets a Foo instead of a Foo*, like this:
fooAPI.processFoo( *pFoo );
Of course, 'pFoo' must be pointing to something reasonable, or dereferencing
it will result in a nasty crash. But then you probably already knew that.
HTH,
- Dennis