Consider the following example:
template<typename T>
class Base
{
public:
inline void fooBase ()
{
T t; // The following error only occurs when class ABC is not defined at the end of the file: "error: t uses undefined class ABC"
}
protected:
};
class ABC;
class DEF;
class Derived : public Base<ABC>
{
public:
void fooDerived ()
{
DEF def; // error: def uses undefined class DEF
}
};
Derived derived;
void foo ()
{
derived.fooBase ();
}
class ABC {};
class DEF {};
Question(s)
- Why is the compiler happy with class
ABC
only defined at the end of the file? - Why is the definition not needed when declaring
Derived
, nor when declaring the globalfoo
function? - When are member functions of a templated class instantiated? Even when the function is made explicit inline, the function seems to be instantiated (at the end of the file) after the function is called in
foo ()
. - Is this behaviour standard C++? If so, does it depends on the C++ version used?
Note that fooDerived
generates an error as expected: the class should be (fully) defined before it is used.
Note that it is not necessary to answer all the questions separately, as they are rather different formulations of the same question.
Tested environment:
- MSVC (but I'm interested in cross platform compliance.)
- It seems to work (except for
DEF def;
as expected) on the three main compilers (GCC, CLang AND MSVC): https://godbolt.org/z/z_c7mc