Bug of the week #10


Welcome to the next pikoTutorial !

The error we’re handling today is a C++ compilation error:

error: ‘class’ has incomplete type

Or a similar one:

error: invalid use of incomplete type ‘class’

What does it mean?

This error occurs in situations when you provide a declaration of a type, but don’t provide definition of that type. For example, if I try to compile the code below:

C++
class SomeType;

void SomeFunction(SomeType input) {}

I’ll get the following error:

error: ‘input’ has incomplete type

Or if the argument is a pointer:

C++
#include <iostream>

class SomeType;

void SomeFunction(SomeType* input)
{
    std::cout << input->GetName();
}

I’ll get the compilation error saying:

error: invalid use of incomplete type ‘class SomeType’

How to fix it?

Provide the full type definition

If you can, just provide a full definition of the problematic type:

C++
class SomeType
{
public:
    std::string GetName() { return "Albert"; }
};

void SomeFunction(SomeType input)
{
    std::cout << input.GetName();
}

Stick to the pointers

If you can’t provide the full definition of the type, but at some place of your program you must declare something else with help of that type (e.g. a function), just use a pointer to that type instead of type directly:

C++
class SomeType;

void SomeFunction(SomeType* input);

Such code compiles because in order to store an address to some type, compiler does not need to know anything about that type, so the full definition is not necessary. Remember however that as soon as you want to use that type (e.g. to call a member function on it), compiler will complain about the full type definition, so in the end, you must provide that definition somewhere in your code base.