Initializing array of pointers to an object in a class constructor

J

John

might I ask...
SomeClass::SomeClass() :
myObjPtrs(123)
{
for(int i=0; i<123; i++)
{
myObjPtrs = std::shared_ptr<MyObj>(new MyObj);
}
}


What is " : myObjPtrs(123)" for?
Is it the same as:

SomeClass::SomeClass()
{
myObjPtrs.resize(123); // (or reserve in case of push_back)
......
}

because with the first version "123" can't be dynamic number but only
defined at compile time...
 
F

Francesco S. Carta

might I ask...
SomeClass::SomeClass() :
myObjPtrs(123)
{
for(int i=0; i<123; i++)
{
myObjPtrs = std::shared_ptr<MyObj>(new MyObj);
}
}


What is " : myObjPtrs(123)" for?
Is it the same as:

SomeClass::SomeClass()
{
myObjPtrs.resize(123); // (or reserve in case of push_back)
.....
}


Yes and no: both resize() and the ctor initialization list (" :
myObjPtrs(123)" in this case) change the size of the vector (they
actually add objects to it) while reserve() just allocates space for
them so that there will be no reallocation when pushing back elements up
to the reserved count of elements.
because with the first version "123" can't be dynamic number but only
defined at compile time...

You can pass that argument to the constructor if you want, such as:
SomeClass::SomeClass(int n) : myObjPtrs(n) {}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top