Re: Initializing array of pointers to an object in a class
constructor
On Jun 24, 9:38 pm, Christian Hackl <ha...@sbox.tugraz.at> wrote:
John ha scritto:
I need an dynamic array of pointers to MyObj in a class.
Am I doing this right?
class SomeClass
{
public: SomeClass();
~SomeClass();
MyObj **pMyObj; // pointer to pointer == pointer to array of
pointers
int iNumPointers; // counter
}
class SomeClass
{
public:
SomeClass(int count);
private:
std::vector<std::vector<MyObj> > vec;
};
Except that he wanted pointers. He didn't say why, so we can't
make any real assumptions: most of the time, pointers are used
for navigation between entity objects, which aren't copiable, so
the vector of object type doesn't work.
Or, if you really need pointers to MyObj (for example if MyObj is a
polymorphic base class):
class SomeClass
{
public:
SomeClass(int count);
private:
std::vector<std::shared_ptr<MyObj> > vec;
};
Again, if the pointers are used for navigation, this is not
a good solution. std::shared_ptr is handing in some specific
cases, but it is definitely not a general solution.
SomeClass::SomeClass()
{
iNumPointers = 123;
pMyObj = new MyObj*[iNumPointers]; // create array of iNumPointers
pointers to MyObj
for (int i = 0; i < iNumPointers; i++) pMyObj[i] = new MyObj(); // init each
pointer object
}
This, on the other hand, makes it look like the vector of
objects *is* the best solution, and that his use of pointers is
wrong.
If MyObj is not polymorphic:
SomeClass::SomeClass(int count) :
vec(count)
{
}
This supposes a default constructor, of course.
If it is polymorphic:
SomeClass::SomeClass(int count) :
vec(count, std::shared_ptr<MyObj>(new MyObjDerived))
{
}
If all of the objects do belong to SomeClass, yes.
SomeClass::~SomeClass()
No destructor needed at all.
But you might want to provide one anyway, for various reasons.
The default destructor is inline.
--
James Kanze