Search code examples
c++language-lawyerc++17return-typeincomplete-type

Incomplete types as function parameters and return values


The following code compiles successfully both with clang++ 5.0.0 and g++ 7.2 (with the -std=c++17 -Wall -Wextra -Werror -pedantic-errors -O0 compilation flags):

struct Foo;

struct Bar
{
    Foo get() const;

    void set(Foo);
};

struct Foo
{
};

Foo Bar::get() const
{
    return {};
}

void Bar::set(Foo)
{
}


int main()
{
    Bar bar{};

    (void)bar.get();
    bar.set(Foo{});
}

Is it valid to use incomplete types as function parameters and return values? What does the C++ say on it?


Solution

  • In a function definition, you cannot use incomplete types: [dcl.fct]/12:

    The type of a parameter or the return type for a function definition shall not be an incomplete (possibly cv-qualified) class type in the context of the function definition unless the function is deleted.

    But a function declaration has no such restriction. By the time you define Bar::get and Bar::set, Foo is a complete type, so the program is fine.