Problem with vector of pointers to struct in C++

Following program, although legal in C++11, may not compile with your current c++ compiler.

#include    <iostream>
#include    <vector>
using namespace std;

int main()
    struct a
        int i;
        int j;

    std::vector<a*> vecA;

    a* pA = new a;

    pA->i = 4;
    pA->j = 9;


    return 0;

It may generates following error and refuse to compile. In function int main()’: error: template argument for template<class _Alloc> class std::allocator uses local type main()::a*’ error:   trying to instantiate template<class _Alloc> class std::allocator error: template argument 2 is invalid error: invalid type in declaration before ‘;’ token error: request for member push_back in vecA’, which is of non-class type int

The answer is that you should declare your struct outside the main function. A local can not be used as a template parameter (i.e. vectror of pointers to struct). For more details, look at this question.


One thought on “Problem with vector of pointers to struct in C++

  1. Indeed, this was a really stupid limitation of C++. Quite often you hit this error and totally stumped as to what the problem is simply because it all looks correct. I’m glad C++11 has relaxed the rules considerably.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s