Reputation: 10109
I'm struggling with the constructor of one of my classes do to a member that is not initialized properly.
I have a class "Settings" that handles the setting I use for my simulations and a class Simulations that performs the simulation steps.
What I can't understand is why this code doesn't 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 can't understand why.
By the way defining v inside the curly brackets works fine, I'm just curious to know why defining it the proper way doesn't work as expected!
Thanks a lot for the help!
Upvotes: 0
Views: 12532
Reputation: 1691
You don't need to create an extra vector and use the copy constructor. Just pass the arguments straight to your vector in the member initializer. As another poster mentioned, did you verify that the return of SP->n is actually not 0? If you hardcode some values in, you'll see that it works fine, as 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))
{
}
Upvotes: 0
Reputation: 798
Also please make sure you check SP is not null pointer. This will otherwise have a crash.
Simulation::Simulation(Settings *pS)
:SP(pS), v(pS != NULL ? pS->n : 0 , 0) {}
This will check for SP not being NULL. this is the case when Simulation(NULL) is used as constructor.
Upvotes: 0
Reputation: 258558
You don't need the extra vector:
Simulation::Simulation(Settings *pS)
:SP(pS), v(SP->n,0) {}
If this doesn't work, this isn't your code. Are you sure SP
is declared before v
in the class definition? If this also doesn't work, try with pS
instead of SP
.
Upvotes: 2
Reputation: 37930
You've verified that pS->n != 0
prior to instantiating the Simulation
, right?
Anyway, I think the line you're looking for in your constructor is:
:SP(pS), v(pS->n, 0) {}
The way you're doing it now is creating a whole std::vector
and then copying it to v
.
Upvotes: 2