Object Lifecycle

Hi,

I am bit confused about when an c++ object gets created.
Does the follwoing statement actually created an object or does it declare an object (without actually creating it)

vector<Matrix> dataVector;

I believe the following line of code actually created a vector where as the statement above does not create and object.
vector<Matrix> dataVector(3);

Could some one let me know if this is correct.


Also if the first statement does not actually create an object, the following function would crash (if the testDataNumber is not equal to 2. Am I right?(In Java this would not be allowed but compiles ok in C++).
vector<Matrix> populateTestMatricesArchDiffusion(int testDataNumber) {
vector<Matrix> dataVector;
if (testDataNumber == 2) {
Matrix A(2,2);
A[0][0] = -1;
A[0][1] = 0.0;
A[1][0] = 0.0;
A[1][1] = -2;
dataVector.push_back(A);
}
return dataVector;
}

And finally,
What should I do to solve the problem.

In Java we can do some thing like below.
vector<Matrix> dataVector = null;

Is there some thing like this in C++

Thanks a lot.

Thusitha
Both vector<Matrix> dataVector; and vector<Matrix> dataVector(3); are valid and both create a vector variable.

vector<Matrix> dataVector; will create an empty vector.

vector<dataVector(3); will create a vector with 3 Maxtrix objects in it. These objects would be constructed
using the Matrix default constructor. (NOTE: if a public default constructor is not available then that line won't compile).


The code will not crash if testDataNumber is not eqaul to 2, it will return the empty dataVector.

Last edited on
Got it. Thanks a lot for the prompt reply.
Topic archived. No new replies allowed.