I'm really new to c++ but I think I know the basics.
For my program I have to manipulate vectors of doubles in a class with another class. So i wrote a test program. Now i see that i can't even access the vector which is defined in the constructor of a class in my main function. I don't get error messages from the compiler, but my program crashes when i execute it.
Sorry if the code looks a bit strange, i had some debug stuff in it to try to find the error.
I can compile the file without an error, but my program aborts when i use vector.at(index). When using vector[index] i get a segmentation violation error. I wonder why i can display b but not a. I hope you understand my problem...
you are working with the local variables and not with the class vector's.
so the class vector size is still zero and when you try the index, it crashes. b is working fine because you have initialized it with the local values which you created in the constructor.
if you want to use the class variable, remove the locals from the constructor and instead use the push_back() on the class vector.
yeah the double quote thing wasn't there originally, i just forgot to remove them again.
Thank you for your quick help.
But why can I assign a value to an integer and just access it and can't do this with a vector?
Are they so different in their behavior? Before doing this i initialized the vector as follows:
1 2 3
vector<double> weight(2); //(so it has the size 2 and empty entries)
weight[0]=1;
weight[1]=2;
That didn't work either.
What does my assignment do instead?
I think my final question is this: Why is the assignment to the vector just local, but the assignment to b not.
Sorry for the newbie questions ^^
and thanks for help
you have two variables in the class which you have declared.
Now you have two more variables in the constructor which are brand new. So now you have four variables running around.
you assign values to these local variables which are in the constructor. that is fine and than from on these vector's/variables you assign to 'b'. that is fine too.
keep in mind that you are not doing anything with the class variables and only working with locals. so the size is increasing for the locals which are in the constructor and nothing is happening to the class variables.
now as soon the constructor exit, the local variables will vanish although the value of 'b' will be there as it will not vanish until the class object is not freed.
now in the main you try to access the class variables but you worked with the locals which have vanished and not present. the class variables were not touched and their size is still zero.
so you will get an access violation as they dont have anything inside them. what you filled was in the locals which are not present.