#include <iostream>
usingnamespace 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??
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.
#include <iostream>
usingnamespace 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;
}