Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why an inline declaration is not an incomplete type?

Consider the code below:

struct Foo {
    struct Bar;
    Foo()
    {
        Bar bar; // Why isn't Bar an incomplete type?!
    }
    struct Bar {}; // Full definition
};

// struct Bar {}; // fails to compile due to incomplete type

int main()
{
    Foo foo;
}

It compiles fine under at least 2 compilers (gcc5.2, clang3.5). My question is:

  • Why isn't Bar considered an incomplete type in the constructor Foo::Foo, as I forward-declare it above the constructor but fully use it inside the constructor?

Whenever I move Foo::Bar outside the class, in other words Bar becomes a stand-alone class, I get the expected

error: aggregate 'Foo::Bar bar' has incomplete type and cannot be defined

like image 900
vsoftco Avatar asked Sep 20 '15 23:09

vsoftco


People also ask

What is an incomplete type?

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.

What does it mean incomplete type in c++?

An incomplete class declaration is a class declaration that does not define any class members. You cannot declare any objects of the class type or refer to the members of a class until the declaration is complete.


1 Answers

Within the member specification the class is considered complete within function bodies, from the draft C++ standard section 9.2 [class.mem]:

A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments, using-declarations introducing inheriting constructors (12.9), exception-specifications, and brace-or-equal-initializers for non-static data members (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification

Which means you don't even have to forward declare Bar (see it live):

struct Foo {
    Foo()
    {
        Bar bar; 
    }
    struct Bar {};  
};

Forward declaring could be useful in avoiding violation of section 3.3.7 paragraph 2 and 3.

like image 193
Shafik Yaghmour Avatar answered Sep 17 '22 03:09

Shafik Yaghmour