Friday, April 4, 2014

C/C++ forward declaration

In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, or a function) for which the programmer has not yet given a complete definition.
In C++, you should forward declare classes instead of including headers. Don’t use an #include when a forward declaration would suffice. When you include a header file you introduce a dependency that will cause your code to be recompiled whenever the header file changes. If your header file includes other header files, any change to those files will cause any code that includes your header to be recompiled. Therefore, you should prefer to minimize includes, particularly includes of header files in other header files.
You can significantly reduce the number of header files you need to include in your own header files by using forward declarations. For example, if your header file uses the File class in ways that do not require access to the declaration of the File class, your header file can just forward declare class File; instead of having to #include “file.h”.
This will in turn speed a little bit the compilation.
Assuming the following forward declaration.
class X;
Here's what you can and cannot do.
What you can do with an incomplete type:
Declare a member to be a pointer or a reference to the incomplete type:
class Foo {
X *pt;
X &pt;
};
Declare functions or methods which accept/return incomplete types:
void f1(X);
X f2();
Define functions or methods which accept/return pointers/references to the incomplete type (but without using its members):
void f3(X*, X&) {}
X& f4() {}
X* f5() {}
What you cannot do with an incomplete type:
Use it as a base class
class Foo : X {} // compiler error!
Use it to declare a member:
class Foo {
X m; // compiler error!
};
Define functions or methods using this type
void f1(X x) {} // compiler error!
X f2() {} // compiler error!
Use its methods or fields, in fact trying to dereference a variable with incomplete type
class Foo {
X *m;
void method()
{
m->someMethod(); // compiler error!
int i = m->someField; // compiler error!
}
};

No comments:

Post a Comment