Re: Vector of Pointers Not working
* Jimbo:
I am trying to store a group of objects in a vector of pointers(of the
same type as the objects) but my simple program is not compiling.
Am I using this vector correcly? vector <object*> objList;
This is a bit off-topic in [comp.os.ms-windows.programmer.win32].
Consequently I've set follow-ups to [comp.lang.c++].
[source]
// Simple example
#include <iostream>
#include <vector>
using namespace std;
class object {
public:
object();
void setCoords(object o);
void getCoords(int &x, int &y);
private:
int x;
int y;
};
vector <object*> objList;
int main() {
// create 4 objects
for (int i=0; i<5; i++) {
object a;
objList.push_back(&a);
}
Don't store addresses to local objects. Each local object ceases to exist at the
bottom of the loop body. Leaving you with addresses of non-existent objects.
// change objects x,y values
for (int i=0; i<5; i++) {
*(objList.at(i)).setCoords(i,i); // error: "No matching call
to object::setCoords....
This would be ...
objList.at(i)->setCoords(i,i);
.... except that supplying two int arguments doesn't match the declaration of the
member routine.
}
int tempX, tempY;
// get & display all objects x,y values
for (int i=0; i<objList.size(); i++)
{
object temp = *(objList.at(i));
temp.getCoords(tempX,tempY); // error: "No matching call to
object::setCoords....
No, that's not what any compiler may report.
cout << tempX, << " " << tempY << endl; // this will output
1,1 for all of them
// when it should be 1,1 2,2 3,3 4,4
}
}
object::object()
{
x = 1;
y = 1;
}
void object::setCoords(int xN, int yN)
{
x = xN;
y = yN;
}
This does not match the earlier declaration.
void object::getCoords(int &xN, int &yN)
{
xN = x;
yN = y;
}
[/source]
Cheers & hth.,
- Alf