[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppForwardDeclaration
What does NOT work, is:
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
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
};
- 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, youTest * 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:After this #include you have a forward declaration of, among others, std::iostream and std::string.
- include <iosfwd>
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.[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
