learner
learner

Reputation: 1219

Pointers passed by reference? (Sanity check)

I am conceptually confused about what I am seeing in following situation: a pointer is passed from main() to function ( func1() ) by reference. func1() then further passes this pointer to func2() also by reference. Now if func2() updates the pointer so that it now points to a new address, this reflects back in main().

Doubts:

1. Is it some sort of pointer-to-pointer-to-pointer in the background?

2. Isn't the reference *&ptr1 and *&ptr2 in func1() being initialized to NULL when ptr1 and ptr2 are passed by reference in main() ? I had read that references cannot be initialized to NULL.

#include <iostream>
using namespace std;

void func2(int *&ptr2)
{
    int var2 = 123;
    ptr2 = &var2;

    cout << endl <<"func2 - ptr2: " << ptr2 << endl;
}

void func1(int *&ptr1, int *&ptr2)
{
    int var1 = 111;
    ptr1 = &var1;
    func2(ptr2);

    cout << endl << "func1 - ptr1: " << ptr1 << "  ptr2: " << ptr2 << endl;
}

int main()
{
    int *ptr1 = NULL;
    int *ptr2 = NULL;
    cout << "main - ptr1: " << ptr1 << "  ptr2: " << ptr2 << endl;

    func1(ptr1, ptr2);
    cout << "main now - ptr1: " << ptr1 << "  ptr2: " << ptr2 << endl;

    return 0;
}

OUTPUT:

main - ptr1: 0  ptr2: 0

func2 - ptr2: 0x28fe3c

func1 - ptr1: 0x28fe6c  ptr2: 0x28fe3c
main now - ptr1: 0x28fe6c  ptr2: 0x28fe3c

Upvotes: 0

Views: 243

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

No, there is no "pointer-to-pointer-to-pointer" in the background?.

There's just a single pointer.

Passing a reference to an object essentially passes a pointer to the referenced object. Then, if that reference is passed as a 2nd reference, the same actual, internal, pointer gets passed, as is. So the second function receives the same internal pointer than the first one.

Upvotes: 3

Related Questions