Initialization of a vector in the constructor - C ++

I am struggling with the constructor of one of my classes to make it a member that is not initialized properly.

I have a Settings class that processes the parameter that I use for modeling and a Simulations class that performs the modeling steps.

I do not understand why this code does not work as expected:

class Settings{ public: int n ; // a number I need to create properly a vector in my class simulation // ... rest of the code constructors etc to read values from files. // everything works fine and the values are assigned properly } class Simulation{ public: std::vector<int> v ; Settings *SP; Simulation(Settings *); } Simulation::Simulation(Settings *pS) :SP(pS), v(std::vector<int>(SP->n,0)) {} // the constructor doesn't work, // v is initialized but it is not created as a vector of size n, but 0. 

I think there is a problem in the way I use the constructor, but I cannot understand why.

By the way, the definition of v inside curly braces works fine, I'm just curious to know why by defining it, the correct way does not work properly!

Thank you for help!

0
source share
4 answers

You do not need an additional vector:

 Simulation::Simulation(Settings *pS) :SP(pS), v(SP->n,0) {} 

If this does not work, this is not your code. Are you sure SP declared before v in the class definition? If this also does not work, try pS instead of SP .

+2
source

You confirmed that pS->n != 0 before creating the Simulation instance, right?

Anyway, I think the line you are looking for in your constructor is:

 :SP(pS), v(pS->n, 0) {} 

Now you create the whole std::vector , and then copy it to v .

+2
source

Also make sure that you check that the SP is not a null pointer. Otherwise, it may be a failure.

 Simulation::Simulation(Settings *pS) :SP(pS), v(pS != NULL ? pS->n : 0 , 0) {} 

This will verify that the SP will not be NULL. this is the case when simulation (NULL) is used as the constructor.

0
source

You do not need to create an additional vector and use the copy constructor. Just pass the arguments directly to your vector in the member initializer. As another poster mentioned, did you confirm that the return of SP-> n is actually not 0? If you copy some values, you will see that it works fine, as shown below:

 #include <iostream> #include <vector> using namespace std; class foo { public: foo(); vector<int> vec; }; int main() { foo obj; for(int i=0;i<obj.vec.size();++i) { cout << obj.vec[i] << ' '; } system("pause"); return 0; } foo::foo() :vec(vector<int>(10,2)) { } 
0
source

All Articles