Tuesday, July 25, 2006

How to call the constructors in vector

CMyClass(int ,int):- is the default constructor
std::vector <CMyClass> oTest(2,CMyClass(2,3));
The above line will create 2 objects of type CMyClass and calls the constructor with the params 2 and 3.

5 comments:

Anonymous said...

Is there any way to call different constructors(different params) for indivitual items in the vector ??

FarPointer said...

Well vectors are for holding objects of the same type ( logically i mean of the same construction style), but i dont think we can call for different constructors in vector .Anyway we have placement new operator to call for any objects.:)

Anonymous said...

yup, you can. Have a base class, lets call it CBase.Derive two classed from CBase call them CBaseDerived and CBaseDerived1

now you can do this:-
vector  <CBase> vec;
CBaseDerived  t1;
CBaseDerived1 t1;
vec.push_back(t);
vec.push_back(t1)

The above should work.Normally it is recommeded to have a vector of pointer to objects, something like this:-
vector <CBase *> vec; and then create the objects using new and then add it to the vector, this avoids the copy constructor from being called when managed by the vector.

FarPointer said...

Yes we should use pointer's as you have mentioned it avoids copyconstructor and helps in more OOps oriented way.

Anonymous said...

looks like I deviated from your original topic. Anyway I did make a point you may want to explore.