I have a header file (say the_foo.h) which defines/declares the following classes:
// \file the_foo.h
class FooBase
{
virtual size_t bar_size() = 0;
};
template<class Bar>
class Foo : public FooBase
{
size_t bar_size() { return sizeof(Bar); }
};
class TheBar; // TheBar forward declaration
class TheFoo : public Foo<TheBar>
{
};
Compiling with MS vc14 (Visual Studio 2015), I notice the following behaviors:
Any cpp file which includes the_foo.h and defines
TheBar
, eg:#include "the_foo.h" class TheBar {}; // TheBar definition
will compile just fine. However,
Any cpp file which includes the_foo.h and DOES NOT DEFINE
TheBar
, eg:#include "the_foo.h"
fails to compile with error:
the_foo.h(11): error C2027: use of undefined type 'TheBar'
The cpp file compiled above contains one single line: inclusion of the header, no more code.
Removing the virtual member function declarationvirtual size_t bar_size() = 0;
does fix the error.
Thanks to answer from Sam Varshavchik, this code compile fine using gcc 5.3.1, so this issue is clearly compiler specific.
My questions are:
- Why does compilation fail in case (2), when
TheBar
is forward declared only ? - Is there any way to make case (2) compiling successfully under vc14, i.e. without an explicit definition of
TheBar
, which class I need to keep opaque in some cpp files ?
PS: I edited the code sample of this question in order to make clear what actually causes the issue described in the question. The original code sample (which is quoted in the answer from Sam Varshavchik) may indeed have misleaded on the actual cause of the issue and, consequently, leaded to answers and comments out of the question scope.