views:

389

answers:

2

I initialized a vector of pointers called "antiviral_data", and am able to use antiviral_data.push_back without problems. But when I try to do the same thing with "viral_data" I get an error, because the compiler thinks I am redeclaring "viral_data":

vector<virus*> viral_data;
vector<virus*>::iterator vI;
viral_data.push_back(new X1(9, 9, 'X')); //I get the error on this line
vector<antivirus*> antiviral_data;
vector<antivirus*>::iterator aI;

(FYI: antiviral_data is in another function, this is a header file)

EDIT: X1 is a class derived from virus.

A: 

Well, I figured out the answer to my question about thirty seconds after I posted it, apparantly you can't use any function outside of main() or another function, so you have to put .push_back() in a different function.

Keand64
That is not exactly true.
anon
Right. Anything you want to do should either be in main() or in another function that gets called (directly or indirectly) from within main(). You can, however, declare and define global variables outside of main(). Although using global variables is often not a good idea.
MatrixFrog
Thats where I got confused. In the final version of my program, these declarations are going to be in an init() function, so I forgot that they were global and just assumed that it would work.
Keand64
@MatrixFrog: that comment should have been poured into an answer. Although you can call functions, even with side-effects, to initialize global variables, too.
xtofl
+1  A: 

If the compiler tells you it thinks you're redeclaring a name, maybe you should wonder why it thinks so.

Probably, it's because you did redeclare the name.

Since you have the code in a header file, chances are you include that file twice. Line numbers in error messages are not always so very accurate...

If that would be the case, you can get help from so called "include guards": prepend the header file with something like

#ifndef HEADER_INCLUDED
#define HEADER_INCLUDED 
...
... your actual header
#endif

(or on VC, you can use

#pragma once

)

xtofl