#include <iostream>
#include <vector>
#include <cassert>
class a_class
{
public:
int num_IN;
a_class():num_IN(0){}
a_class(a_class const & origin){/*Initialise();*/} //if not called here, error occurs
void Initialise(){num_IN =5;}
};
int main ()
{
std::vector <a_class> the_vector;
for(int q=0; q < 30; q++)
{
the_vector.push_back(a_class());
the_vector[q].Initialise();
assert(5 == the_vector[q].num_IN); //no problem here
}
for(int q=0; q < 30; q++)
assert(the_vector[q].num_IN == 5); //assertion fails
}
I don’t understand the difference between calling this from outside vs. inside the CC. I also don’t know why it should cause a problem in any case.
std::vectormay reallocate the buffer it uses if it’s size outgrows it, in which case it has to copy the old elements over to the new buffer. If you don’t have a proper copy constructor that copiesnum_INover, the old value is lost.Fix this by providing a proper copy constructor:
In the code posted the copy constructor isn’t even needed – if you don’t provide one the compiler will generate a suitable one here.