PDA

View Full Version : Initializing a vector of pointers


bsherwood
10-15-2005, 05:19 PM
I'm a novice in C++ with a little more Java experience. I've been trying to teach myself C++ and have hit some bumps.

I have a vector of pointers to objects. Whenever I try to initialize it with a for loop I end up with a vector full of pointers pointing to the same object.

Here is what I have done:

for (i = 0; i < max; i ++){

tmpObject = Object(i);
tmpPoint = &tmbObject;
PointerVector[i] = tmpPoint;
}

I understand why this ends up with a vector full of pointers to Object(max-1). How do I fill it up with a vector full of pointers to different Objects?

Thanks.

aman
10-16-2005, 01:59 AM
Here I'll return a pointer to my object and store it directly in the vector. Perhaps reading the code will help you some.


#include <iostream>
#include <vector>
using namespace std;

class OBJECT {
public:
int index;
};

class CObject {
public:
CObject(int n);
~CObject();

OBJECT* operator()(int i);

private:
OBJECT* m_pObject;

int m_nObjects;
};

CObject::CObject(int n)
{
m_nObjects = n;
m_pObject = new OBJECT[m_nObjects];

for(int i = 0; i < m_nObjects; i ++ )
{
m_pObject[i].index = i;
}
}

CObject::~CObject()
{
delete[] m_pObject;
}


OBJECT* CObject::operator()(int i)
{
return &m_pObject[i];
}


int main()
{
vector<OBJECT*> PointerVector;

int max = 10;
CObject Object(max);

int i;
for (i = 0; i < max; i ++)
{
cout << "Pushing object 0x" << Object(i) << endl;
PointerVector.push_back(Object(i));
}

for (i = 0; i < max; i ++)
{
OBJECT * tmpObject = PointerVector[i];

// tmpObject points to *Object(i)
cout << "Pointer to Object " << tmpObject->index << endl;
}

return 0;
}