Bug of the week #10
pikoTutorial

pikoTutorial @pikotutorial

About: Inspired by the SI unit prefix “pico” (10^-12), this place aims to deliver short and targeted tutorials which can speed up work of every software engineer.

Joined:
Dec 14, 2024

Bug of the week #10

Publish Date: Jul 15
0 0

Welcome to the next pikoTutorial!

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

error: ‘class’ has incomplete type
Enter fullscreen mode Exit fullscreen mode

Or a similar one:

error: invalid use of incomplete type ‘class’
Enter fullscreen mode Exit fullscreen mode

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:

class SomeType;

void SomeFunction(SomeType input) {}
Enter fullscreen mode Exit fullscreen mode

I'll get the following error:

error: ‘input’ has incomplete type
Enter fullscreen mode Exit fullscreen mode

Or if the argument is a pointer:

class SomeType;

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

I'll get the compilation error saying:

error: invalid use of incomplete type ‘class SomeType’
Enter fullscreen mode Exit fullscreen mode

How to fix it?

Provide the full type definition

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

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

void SomeFunction(SomeType input)
{
    std::cout << input.GetName();
}
Enter fullscreen mode Exit fullscreen mode

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:

class SomeType;

void SomeFunction(SomeType* input);
Enter fullscreen mode Exit fullscreen mode

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.

Comments 0 total

    Add comment