[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppForwardDeclaration

(C++) Forward declaration

A technique to speed up the time compiling by saying that a class exists and will get defined later.

class Test; //Forward declaration
class MyClass
{
  public:
  Test * mTest; //Okay: a pointer to this class can be made
};
  1. include "Test.h" //Okay: the class definition comes in later
int main() { MyClass myClass; myClass.mTest = new Test; //Okay: use class methods after class definition delete myClass.mTest; }


Using a forward declared class

When a class is forward declared, you
  Test * myTest;
  Test myTest; //ERROR: 'Class Test unknown or unknown size'
  Test * myTest = new Test; //ERROR: 'Class Test unknown'
this would call the constructor)

The cause of this speed increase

The increase in speed by forward declaration is due to the fact that header files (.h) are #included multiple times, whereas implementation files .cpp are not. Therefore, keep the header files as simple to compile as possible.

STL forward declarations

The STL also has build-in forward declarations:
  1. include <iosfwd>
After this #include you have a forward declaration of, among others, std::iostream and std::string.

Forward declaration in other namespaces

A forward declaration in other namespaces can also be done using the example below:

//Forward declaration
namespace AnyNamespace //Get in the right namespace
{
  class MyForwardDeclaredClass; //Forward declaration
};


What does NOT work, is:

AnyNamespace::MyForwardDeclaredClass; //DOES NOT WORK!!!


Idioms using forward declarations

The pimpl-idiom speeds up any class's compilation by forward declaring the class's own implementation.

last edited (November 11, 2006) by bilderbikkel, Number of views: 3519, Current Rev: 8 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.