user3205479
user3205479

Reputation: 1533

Forward declaration of class leads to incomplete type error

Why does it generate error in case 1 but not in case 2? Having done forward declaraion compiler treats it other way? I think its just a declaration for compiler to search for class apple entire file.

// CASE 1
class apple; // forward declaration

class fruit{
    apple b; // error: incomplete type but why? there is no recursion I guess
};

class apple{
   public: int a;
};

int main(){
   fruit f;
   return 0;
}

// CASE 2
class apple{
   public: int a;
};

class fruit{
   apple b; // no error works fine
};

int main(){
  fruit f;
  return 0;
}

Explain me how. Any help is greatly appreciated.

Upvotes: 1

Views: 2297

Answers (2)

Yu Hao
Yu Hao

Reputation: 122493

After the forward declaration and before the definition, the class fruit is indeed an incomplete type.

You can only use it in limited ways, e.g, to define pointers or references to such types, or to declare(but not define) functions that use an incomplete type as a parameter or return type. However, in your code, you are using fruit type, not a pointer or reference to it, so it's illegal.

Upvotes: 2

Eric
Eric

Reputation: 19873

Forward declarations have to use pointers. The following should compile

class fruit{
    apple* b; // error: incomplete type but why? there is no recursion I guess
};

The reason for that is that when creating the class fruit, the compiler needs to know how much memory it will allocate for its members. In case it is a pointer this is easy, either 32-bits or 64-bits depending on your architecture. This is why forward declaration works.

If you try to allocate a full object there, then the compiler needs to know how large apple will be to reserve memory for it. But since it is only a forward declaration it has no knowledge of that size and shows an error

Upvotes: 4

Related Questions