rsk82
rsk82

Reputation: 29377

how to assign vector to object by reference?

My try:

class myClass {
  std::vector<int> myVector;
 public:
  myClass(std::vector<int> &v) {
    this->myVector = v;
  }
  void doSomething() {
    for (int &num : this->myVector) {
      num += 100;
    }
  }
};

in main():

vector<int> myVect = {1,2,3,4};
myClass myClassInst(myVect);
myClassInst.doSomething();

but then checking:

for (int i : myVect) {
  printf("%i\n", i);
}

Makes no change to the original vector.

Upvotes: 2

Views: 4340

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153820

If you want to store a reference to another object in your class, you need to use something which actually refers to the original object. References look like the obvious choice but they are poor data members! Instead, you want to use a pointer:

class myClass {
    std::vector<int>* myVector;
public:
    myClass(std::vector<int>& vector): myVector(&myVector) {}
    void doSomething() {
        for (auto& num: *myVector) {
            num += 100;
        }
    }
};

Upvotes: 5

Related Questions