Doidel
Doidel

Reputation: 319

Vector in class is empty in referenced class

I could condense my issue into the following problem:

Class1 x;
Class1 y;
x.Label = "Test";
y = x;
x.myVector.push_back("test");

Result: x.myVector.size() == 1, y.myVector.size() == 0, yet both have the label “Test”!

I'm relatively new to C++, but unfortunately I couldn't figure the issue out by searching in the internet...

Thanks for your help!

Upvotes: 0

Views: 104

Answers (3)

Ruks
Ruks

Reputation: 3956

Result: x.myVector.size() == 1, y.myVector.size() == 0, yet both have the label “Test”!

Both are supposed to have the same label because you have:

x.Label = "Test";
y = x; // 'x' and 'y' are now same...

Which copies the instance of x to y... But this:

x.myVector.push_back("test"); // x is now 'test'

comes after the copy... so, it only applies to x not y... and since vectors are empty (so, size() is obviously 0) at initialization like most of the STL classes...

Note: C/C++, in code, goes forward and never looks backward, until and unless the programmer forcibly drags it back using goto, loops, or something similar...


Edit: What you might have thought would might have been for references, so:

Class1 y;
Class1& x = y;
x.Label = "Test";
// y = x; Eh, redundant statement
x.myVector.push_back("test");

Does what you think it should do...

Upvotes: 1

nvoigt
nvoigt

Reputation: 77294

Your example is far from complete, so I will just assume the simplest way for it to compile:

// creates an instance named x on the stack
Class1 x; 

// creates an instance named y on the stack
Class1 y; 

// sets the label of the x instance to "Test"
x.Label = "Test"; 

// COPIES all data from x over to y (including the label)
y = x; 

// inserts into the vector of x, as the copy has gone through already, this is in x only
x.myVector.push_back("test"); 

Upvotes: 2

Blaze
Blaze

Reputation: 16876

Class1 x;
Class1 y;

Here you are making your two objects. Both have no label and an empty vector.

x.Label = "Test";

Now x has the label "Test".

y = x;

Without seeing how = is implemented for Class1, it's impossible to say for sure what's happening here. If the compiler implements it, then it probably just copied everything over, so now both y and x have the label "Test", and none of the vectors contain anything yet.

x.myVector.push_back("test");

Now x.myVector contains "Test". However, this doesn't affect y (or y.myVector). That's why y.myVector.size() is 0, you didn't put anything in there, so it still doesn't contain anything.

Upvotes: 1

Related Questions