passing objects by pointer and by reference

Hi there!

Could someone explain to me what is the difference between passing objects by pointer and by reference? Let's see this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#include <iostream>

using namespace std;

class Test {
public:
	
	int var;
	Test( int v = 0) {
		var = v;
	}
};

void alterByReference(Test &t)
{
	Test t2(2);
	t = t2;//this alters the object
}

void alterByPointer(Test *t)
{
	Test t2(2);
	t = &t2;//this does not alter the object, why?
}

int main() {
	Test t1(1);
	
	alterByReference(t1);
	cout <<"By reference. val = "<< t1.var<< endl;
	
	alterByPointer(&t1);
	cout <<"By pointer. val = "<< t1.var<< endl;//t1.var is still 1, why?
	
	return 0;
}


The function 'alterByPointer' does not change the value of the object, but the funcion 'alterByReference' alters the value. Why??

Thanks a lot!



The function 'alterByPointer' does not change the value of the object, but the funcion 'alterByReference' alters the value. Why??


because 'alterByPointer' passes the pointer by value. Which means you are making a copy of the pointer, and passing the copy to 'alterByPointer'. You then change the value of the copy, not the original.

In alterByPointer you are setting the pointer equal to a local variable, and then destroying the variable.

'alterByPointer' and alterByReference both change the value to 2. So I'm not sure how you would be able to tell if alterByPointer worked anyways.



try this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>

using namespace std;

class Test {
public:

	int var;
	Test( int v = 0) {
		var = v;
	}
};

void alterByReference(Test &t)
{
	Test t2(2);
	t = t2;//this alters the object
}

void alterByPointer(Test *&t)
{
    if(t != nullptr)
    {
        delete t;
        t = new Test(6);
    }
}

int main() {
	Test t1(1);

	alterByReference(t1);
	cout <<"By reference. val = "<< t1.var<< endl;


	Test *t2 = new Test(1);
	alterByPointer(t2);
	cout <<"By pointer. val = "<< t2->var<< endl;//t1.var is still 1, why?

    delete t2;
	return 0;
}
Last edited on
In alterByPointer you modify the pointer, but the object that it pointed to at the beginning of the function is not changed.
Last edited on
Hi Yanson,

Thank you very much for your help!

Just one more question, why are you using a reference in the parameter of 'alterByPointer'? If you remove the '&' the result is the same.
Topic archived. No new replies allowed.