Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does an Incomplete Type error occur in C++

Can anyone tell me when does a c++ compiler throw an "incomplete type error"?

Note: I have intentionally left this question a little open ended so that I can debug my code myself.

like image 922
Nickal Avatar asked Jul 07 '17 05:07

Nickal


People also ask

What is an incomplete type in C?

An incomplete type is a type that describes an identifier but lacks information needed to determine the size of the identifier. An incomplete type can be: A structure type whose members you have not yet specified. A union type whose members you have not yet specified.

Why void is an incomplete type?

void is not a complete data type. Because a data type gives the form to which variable is to be stored. But void means nothing. Its like when you have no form to which variable to be stored to return a value than how can you expect a function to return a value...

What is invalid use of incomplete type C++?

Solution: There are multiple possible issues, but in general this error means that GCC can't find the full declaration of the given class or struct.


1 Answers

This happens usually when the compiler has seen a forward declaration but no full definition of this type, while the type is being used somewhere. For example:

class A;

class B { A a; };

The second line will cause a compiler error and, depending on the compiler, will report an incomplete type (other compilers give you a different error, but the meaning is the same).

When you however just use a pointer to such a forward declaration no complain will come up, since the size of a pointer to a class is always known. Like this:

class A;
class B {
   A *a;
   std::shared_ptr<A> aPtr;
};

If you ask what could be wrong in a concrete application or library when this error comes up: that happens usually when a header is included which contains the forward declaration, but full definition hasn't been found yet. The solution is quite obvious: include also the header that gives you access to the full type. Sometimes you may also simply have no or the wrong namespace used for a type and need to correct that instead.

like image 50
Mike Lischke Avatar answered Sep 28 '22 17:09

Mike Lischke