Is it possible to forward declare a class, and actually specify its size, such that in that same header I can use the class in a class definition?
For instance something like:
class Foo = 3 * sizeof(int);
class Bar
{
Foo foo;
};
Instead of having to #include "Foo.h", where that would be something like:
class Foo
{
int a, b, c;
};
FYI: no worries, I'd never want to do something like this (hopefully), I'm just being curious. Note that for forward declaring enum classes the above is possible, which sounds a bit similar.
No this is not possible.
Note that the compiler needs the complete type for instantiation an object not only for knowing the size but also to know which constructors and destructors have to be used, in your example this would only be a problem if a constructor or destructor has to be generated for Bar. There may also be alignment restrictions for Foo on a given platform.
In your case the compiler may have to generate default constructor(s) and a destructor for Bar. If Foo happens to have a non-trivial constructor and/or destructor, default or explicitly specified, that must be called in those constructors/destructors.
Comments have already mentioned that for enum classes, the complete type is in fact specified sufficiently by the forward declaration: the enum cannot have a constructor or destructor and its size and alignment restrictions are also known from the underlying integer type.
I presume the decision not to allow this was made because if class definitions could be spread around in different files, ensuring consistency would make the build process more complex and different from C. Note that C++ can be linked with rather "dumb" linkers, just like C, not actually caring about types and just filling in the right addresses for symbols (I'm simplifying a bit of course).
Not checking consistency would be very risky indeed if we could specify the size of a class in one file and then forget updating it when we add a member in another. The way it is the "one-definition-rule" says basically that anything can happen if a class has more than one non-identical definition in a program.