Initialising a vector of object pointers
Sep 26, 2008 at 8:57pm UTC
Hi,
I have a problem when I try to make a vector with pointers to objects of my class Ball.
The line that generates an error is the fourth line below.
1 2 3 4 5 6
Ball b1(50,70);
Ball b2(100,200);
vector<Ball*> bVect;
bVect.push_back(&b1);
The error I get is
error C2143: syntax error : missing ';' before '.'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2371: 'bVect' : redefinition; different basic types
I am just starting to learn c++ and I can't find the answer in any of my material or online.
Thanks
Sep 26, 2008 at 10:15pm UTC
You have a problem elsewhere in your code. It appears you've defined the "bVect" somewhere above there and that is causing all the problems.
Sep 27, 2008 at 12:22pm UTC
Thanks for the reply.
Here is the complete code of the class, this is all in main.cpp before the main function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#include "main.h"
#include <vector>
using namespace std;
class Ball
{
public :
Ball(float x, float y);
float x,y,xv,yv;
int r,c; //radius and color
};
Ball::Ball(float X, float Y) {
x = X;
y = Y;
xv = 1;
yv = 1;
r = 20;
c = 2;
}
Ball b1(50,70);
Ball b2(100,200);
vector<Ball*> bVect;
bVect.push_back(&b1);
It looks like I could have been mistaken and the error pointed to the line
bVect.push_back(&b1);
It does now anyhow. If I comment the line out, the program compiles.
Edit:
Looks like I cannot declare or access the vector outside the main function, but if i declare it inside of main() I can access it there.
But I want it to be global so I can access it from my update() function.
Do I need to pass a reference to the vector each time I call update() ?
Last edited on Sep 27, 2008 at 12:52pm UTC
Sep 27, 2008 at 12:56pm UTC
You can't call functions (such as std::vector::push_back()) from global scope. Only functions (such as main()) may call functions.
Sep 27, 2008 at 1:16pm UTC
I see, thanks!
Topic archived. No new replies allowed.