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.

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

So.. I can use pointer to undefined class, but cant create object until body appears?
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.

Comments

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;
};

1 Comment

How to use references to incomplete type? Except as function return value?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.