"E.T. Grey" <ne****@alpha-centauri.comwrote in message
news:YN********************@bt.com...
Can I pass a pointer instead of a reference (and vice versa)? - I know a
reference and a pointer are not the same - but i can't help feeling I can
"get away with this".
It depends on where you want to pass it. If a function or method expects a
reference then you couldn't pass a pointer to it, but you could modify the
function/method to accept a pointer instead.
Bad practise, ok practise, or must be avoided at all times?
Useful practice in some instances.
If must be avoided, can I hust take the address of a reference and use
that as a pointer? (actually, its mre useful if I can pass a pointer as
reference
Hopefully this code shows you what you are asking about.
#include <string>
#include <iostream>
void MyRefF( int& IntR )
{
// How to use IntR as a pointer? This works for me.
int* IntP = &IntR;
*IntP = 20;
std::cout << *IntP << std::endl;
}
int main()
{
int* MyIntP = new int(10);
// So how do we pass MyIntP to MyRefF? Dereference it.
MyRefF( *MyIntP );
std::cout << *MyIntP << std::endl;
delete MyIntP;
MyIntP = NULL;
// Following is undefined behavior, and gives me illegal memory access
// when the variable is used inside of MyRefF
MyRefF( *MyIntP );
std::string wait;
std::getline( std::cin, wait );
}
PS: Alarm bells ringing though - a ptr can be null, whereas a reference
can't be .. Hmmmm, looks like "terra infestus" (dangerous ground) to me
...
And you are right to think that, as the code shows.