I have a class Thing with a constructor Thing::Thing() and a method Thing::print(). I am trying to create arrayOfVectors such that each std::vector within the array is of size 0. The constructor function prints out the sizes of each vector correctly but the print() method does not.
I have tried calling arrayOfVectors[n].clear() and arrayOfVectors[n].assign(0,0) on each vector within the array but did not work.
Thing.hpp
class Thing {
private:
std::vector<int>* arrayOfVectors;
public:
Thing();
void print() const;
};
Thing.cpp
Thing::Thing() {
std::vector<int> arrayOfVectors[5];
std::cout << arrayOfVectors[0].size() << std::endl; // 0
std::cout << arrayOfVectors[1].size() << std::endl; // 0
std::cout << arrayOfVectors[2].size() << std::endl; // 0
std::cout << arrayOfVectors[3].size() << std::endl; // 0
std::cout << arrayOfVectors[4].size() << std::endl; // 0
}
void Thing::print() const {
std::cout << arrayOfVectors[0].size() << std::endl; // 0
std::cout << arrayOfVectors[1].size() << std::endl; // 35183230189065
std::cout << arrayOfVectors[2].size() << std::endl; // 33
std::cout << arrayOfVectors[3].size() << std::endl; // 35
std::cout << arrayOfVectors[4].size() << std::endl; // 108
}
main.cpp
int main() {
Thing thing;
thing.print();
return 0;
}
std::vector<int> arrayOfVectors[5];. There was a typo.std::vector<int> arrayOfVectors[5];creates a local variable in the constructor that no longer exists when the constructor finishes. This does not have any connection to the class member with the same name.arrayOfVectorsis a pointer that is not initialized when you call print()