Reputation: 5259
I am looking at a code snippet and I have this sequence.
class MyVariable {
....
CustomType z;
....
}
A.cpp
calling a function f ( & myVariable)
In an included file I do have this :
B.h
void f ( MyVariable * myVariable);
B.cpp
f( MyVariable * myVariable){
CustomType & x = myVariable ->g();
}
where g is a method of the class MyVariable and the implementation is is :
CustomType & g() {
...
return z; //where you can find z in the class
}
It looks pretty complicated to me though, so my question is :
Does any change to x being reflected to the myVariable that is used as a parameter in the function call in A.cpp?
In other words, if in B.cpp, I do something like this :
// change x with some value
Will that change be reflected in the myVariable as well?
Upvotes: 0
Views: 72
Reputation: 76
Whenever the variable is passed either by reference or by address, any change to that variable in called function are reflected in caller function. To answer your question, Yes any change to X will be reflected to myVariable and that applies even if X is private variable.
Upvotes: 0
Reputation: 2757
Yes as the variables address is passed any change of x within the function changes the value of the variable with which function is called.Both the of the pointers refer to the same memory location.So change in the value of one changes the others value automatically.
Upvotes: 1
Reputation: 2334
Yes. There's no copy anywhere as you're either using pointers or references when you “pass” the variable from one place to another, so you're actually using the same variable everywhere.
In g()
, you return a reference to z
, then in f()
you keep this reference to z
. Moreover, when you call f()
, you don't even copy myVariable
, but its address (in the form of a pointer), so you'll actually modify the z
member of the myVariable
variable you have in A.cpp
.
Upvotes: 1
Reputation: 65600
x
is a non-const reference to the z
member of myVariable
, so yes, if you change x
, myVariable->z
will change as well.
You can think of references as aliases, x
is just another name for myVariable->z
.
Upvotes: 1