1

This is weird. I created a vector just fine in one class but can't create it in another class. He's a representation of what I have:

main.h

#include <Windows.h>
#include <ShellAPI.h>
#include <vector>
#include <string>
#include <iostream>

#include "taco.h"

class MyClass
{

public:
    int someint;
    vector<int> myOrder;
};

taco.h

#include <vector>

class OtherClass
{

public:
    vector<int> otherOrder;
};

And I get compile errors regarding the vector declaration in taco.h:

error C2143: syntax error : missing ';' before '<'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2238: unexpected token(s) preceding ';'

What am I missing here? I can uncomment out that second vector declaration and it compiles fine.

Jake Wilson
  • 88,616
  • 93
  • 252
  • 370
  • 5
    This suggests to me that some .h file has `using namespace std;` in it somewhere, which is generally a Bad Idea. `using` should never be done in headers, as it messes up namespaces for any .cpp file that directly or indirectly includes that header. Leave `using` for the source files only, where the effects are local. – David Thornley Jul 28 '10 at 18:09

4 Answers4

13

Try:

std::vector<int> otherOrder;

vector is part of the std namespace. This means that whenever you use a vector in a header file, you should include the std:: prefix.

The reason that you can sometimes get away with forgetting it is that some included files may have using namespace std; in them, allowing you to leave off the prefix. However, you should avoid the using keyword in header files, for it will pollute the namespace of any files that include it.

For a more detailed explanation of the dangers of using namespace ..., see this thread.

Community
  • 1
  • 1
Justin Ardini
  • 9,768
  • 2
  • 39
  • 46
  • 1
    [This answer](http://stackoverflow.com/questions/2879555/c-stl-how-to-write-wrappers-for-cout-cerr-cin-and-endl/2880136#2880136) is another argument against `using namespace std`. – sbi Jul 28 '10 at 18:10
  • Hmmm for some reason I thought my "using namespace std" in main.h would cascade down to taco.h. Thanks for the answer! – Jake Wilson Jul 28 '10 at 18:17
  • @Jakobud: If you had the reverse (`using namespace std;` in `taco.h` but not `main.h`), it would. The only way for it to "cascade" is through `#include`. – Justin Ardini Jul 28 '10 at 18:18
4

Try std::vector<int>. You're supposed to use the namespace --- I'm assuming you have

using namespace std;

in the main.h someplace. There's a lot of talk on SO as to why using using is bad practice ; I'd recommend that you check it out.

Jacob
  • 34,255
  • 14
  • 110
  • 165
4

All C++ standard library objects live in the std namespace. Try

class MyClass
{

public:
    int someint;
    std::vector<int> myOrder;
//  ^^^^^
};
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
1
std::vector<int> ?
a1ex07
  • 36,826
  • 12
  • 90
  • 103