Reputation: 118
I have just found out that this code is legal in header files (at least) in VS 2010
class AClass; //forward declaration of AClass (incomplete type);
class UseAClass
{
public:
AClass returnAClass(); //return a copy of incomplete type - AClass ???
}
Could someone explain me why can I write this?
Upvotes: 3
Views: 417
Reputation: 361472
It is allowed because the knowledge of the size of AClass
is not required by the compiler at the point of declaration of the function which returns AClass
. However, if you attempt to provide a definition of the function there (or make a member of type AClass
in the class UseAClass
), then sizeof(AClass)
is required by the compiler, and thus you need to include the header file in which AClass
is defined. You can also do this:
void acceptAClass(AClass obj); //only the declaration, NO DEFINITION!
Note that this technique is often used to break the cyclic dependencies of headers, as this doesn't require some headers to be included in .h
file : just forward declaration is enough. And in the .cpp
file, you include the header and provide the definitions.
Upvotes: 5