C++ Vector of Pointers help

Associate
Joined
22 Dec 2004
Posts
1,194
Location
Paderborn DE / TeessideUK
Code:
#include<iostream>
using namespace std;
#include <vector>  

class Object{
      public:
             Object(int, int);
             void printDetails();
      private:
              int x;
              int y;
              };
      
Object::Object( int xnum, int ynum)
{
            x = xnum;
            y = ynum;
}


void Object::printDetails()
{
     cout << x << " , " << y;
}

int main()
{
    vector<Object*>lolvector;
    
    for ( int z = 0; z != -1; z++) //starting for loop
    {
        int x, y;
        cout << "x = ?"; //reading in the variables
        cin >> x;
        cout << "y = ?";
        cin >> y;
        
        Object *intptr;
        intptr = new Object(x,y);
        lolvector[z] = intptr;
    }

}

Right so. Im trying to take input from the keyboard and insert it into objects to which then i am filling a vector with pointers to these objects. Can anyone see anything wrong with this. I ask as i cant figure out how to even test it. I thought it would be along the lines of :

lolvector[1].printDetails();

But it gives me errors and i cannot find any information on it in my notes so any help would be appreciated.

TY ocuk
Firthy
 
You're adding the objects into the vector in the wrong way. You use the push_back() function, ie:

lolvector.push_back(intptr);

And the container doesn't know what it's holding, so you need to do some type of cast (static casting probably). Look it up.
 
You're adding the objects into the vector in the wrong way. You use the push_back() function, ie:

lolvector.push_back(intptr);

And the container doesn't know what it's holding, so you need to do some type of cast (static casting probably). Look it up.

right i thought i had to use something along the line of pushback and i do beleive i know static casting etc, forcing a variable to be of a certain type right?

What do i need it for in relation to this?
 
Back
Top Bottom