Bernard Bernard - 1 year ago 65
C++ Question

Why can't a forward declaration be used for a std::vector?

If I create a class like so:

// B.h
#ifndef _B_H_
#define _B_H_

class B
int x;
int y;

#endif // _B_H_

and use it like this:

// main.cpp
#include <iostream>
#include <vector>

class B; // Forward declaration.

class A
A() {
std::cout << v.size() << std::endl;

std::vector<B> v;

int main()
A a;

The compiler fails when compiling
. Now the solution I know is to
#include "B.h"
, but I'm curious as to why it fails. Neither
's error messages were very enlightening in this matter.

Answer Source

The compiler needs to know how big "B" is before it can generate the appropriate layout information. If instead, you said std::vector<B*>, then the compiler wouldn't need to know how big B is because it knows how big a pointer is.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download