2

Can I use forward declaration for template class?
I try:

template<class que_type>
class que;
int main(){
    que<int> mydeque;
    return 0;
}
template<class que_type>
class que {};

I get:

error: aggregate 'que<int> mydeque' has incomplete type and cannot be defined.
all
  • 304
  • 5
  • 16

3 Answers3

5

This is not a template issue. You cannot use a type as a by-value variable unless it has been fully defined.

Oliver Charlesworth
  • 260,367
  • 30
  • 546
  • 667
  • So.. I can use pointer to undefined class, but cant create object until body appears? – all Aug 18 '11 at 17:06
4

No. At the point of instantiation, the complete definition of the class template must be seen by the compiler. And its true for non-template class as well.

Nawaz
  • 341,464
  • 111
  • 648
  • 831
2

Forward declaration of a class should have complete arguments list specified. This would enable the compiler to know it's type.

When a type is forward declared, all the compiler knows about the type is that it exists; it knows nothing about its size, members, or methods and hence it is called an Incomplete type. Therefore, you cannot use the type to declare a member, or a base class, since the compiler would need to know the layout of the type.

You can:

1. Declare a member pointer or a reference to the incomplete type.
2. Declare functions or methods which accepts/return incomplete types.
3. Define functions or methods which accepts/return pointers/references to the incomplete type.

Note that, In all the above cases, the compiler does not need to know the exact layout of the type & hence compilation can be passed.

Example of 1:

class YourClass;
class MyClass 
{
    YourClass *IncompletePtr;
    YourClass &IncompleteRef;
};
Alok Save
  • 196,531
  • 48
  • 417
  • 525