bayesianpower
bayesianpower

Reputation: 91

C++ changing reference of variable

I'm fairly new to C++, coming from Java. I read up about pointers and such, but I just wanted to make sure I fully understand. Please forgive this elementary question. If I have this code:

vector<int> S = someVector;
vector<int> bestS = S;
S = anotherVector;

Is bestS reassigned to anotherVector? I wouldn't think so but since I read about how altering the dereferencing of pointer variables would change the underlying data for other pointers to that data, I'm a little unsure.

I guess I'm also asking, do object variable names behave as pointers?

Upvotes: 0

Views: 59

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595752

Is bestS reassigned to anotherVector?

No. The way your example is written, bestS is a complete independent copy of S, so when you assign anotherVector to S, S becomes a new independent copy of anotherVector, clearing the previous data that was stored in S and copying data from anotherVector into S. bestS is completely unaffected by anything you do to S.

Now, had you declared the variables (or at least bestS) as references, THEN it would behave as you are thinking:

vector<int> &bestS = S;

Then any changes to S are reflected in bestS, since bestS would just be an alias for S.

I wouldn't think so but since I read about how altering the dereferencing of pointer variables would change the underlying data for other pointers to that data, I'm a little unsure.

There are no pointers in your example.

do object variable names behave as pointers?

Only if you explicitly declare them as pointers, eg:

vector<int> *S = &someVector; // <-- S points to someVector
vector<int> *bestS = S; // <-- bestS also points to someVector
*S = anotherVector; // <-- changes someVector, changes can be seen via S and bestS

Upvotes: 2

Related Questions