3

In a header file, I have forward declared two members of a namespace:

namespace Foo {
    struct Odp
    typedef std::vector<Odp> ODPVEC;
};

class Bar
{
public:
     Foo::ODPVEC baz; // C2036
};

The error generated by the compiler is:

error C2036: 'Foo::Odp *': unknown size

I'm guessing this is an issue with forward declaring Odp. How can I get around this?

bdonlan
  • 224,562
  • 31
  • 268
  • 324
Nick Heiner
  • 119,074
  • 188
  • 476
  • 699

2 Answers2

4

Don't forward declare Odp. The compiler does not know what the type of std::vector<Odp> is, because Odp isn't yet declared. Give the compiler a full declaration for that class.

jalf
  • 243,077
  • 51
  • 345
  • 550
Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
  • But what if I also want to declare it somewhere else? – Nick Heiner Jun 15 '10 at 00:44
  • @Rosarch: You can declare the class wherever you want. You can only define it once. Define it somewhere where it can be included everywhere that you need the definition. – James McNellis Jun 15 '10 at 00:55
  • Right, but I'm trying to avoid including header files in other header files. – Nick Heiner Jun 15 '10 at 00:56
  • 1
    @Rosarch: If you need the size of the object, then you don't have much choice. Besides, if the header file needs the class definition, the corresponding source almost certainly needs the class definition, so what does it matter? – James McNellis Jun 15 '10 at 00:59
3

std::vector requires full type declaration of the first template parameter because it stores objects by value, not by pointer, and thus requires knowledge of object size. You might get away with forward declaration if you store pointers in the vector, like:

class foo;
typedef std::vector<foo*> foo_ptr_vec;

See the fine documentation for gory details.

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171