2.3. Reducing #includes with Forward Class Declarations

Problem

You have a header file that references classes in other headers, and you need to reduce compilation dependencies (and perhaps time).

Solution

Use forward class declarations where possible to avoid unnecessary compilation dependencies. Example 2-4 gives a short example of a forward class declaration.

Example 2-4. Forward class declaration

// myheader.h
#ifndef MYHEADER_H_  _
#define MYHEADER_H_  _

class A; // No need to include A's header

class B {
   public:
      void f(const A& a);
   // ...
   private:
      A* a_;
};

#endif

Somewhere else there is a header and perhaps an implementation file that declares and defines the class A, but from within myheader.h I don’t care about the details of A: all I need to know is that A is a class.

Discussion

A forward class declaration is a way to ignore details that you don’t need to be concerned with. In Example 2-4, myheader.h doesn’t need to know anything about the class A except that it exists and that it’s a class.

Consider what would happen if you #included the header file for A, or, more realistically, the header files for the half-dozen or so classes you would use in a real header file. Now an implementation file (myheader.cpp) includes this header, myheader.h, because it contains the declarations for everything. So far, so good. If you change one of the header files included by myheader.h (or one of the header files included by one of those files), then all of the implementation files that include ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.