RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Advanced
Aug 8, 2006

Forward Declaration of Classes Within Namespaces

Forward declaration is a handy mechanism for reducing the number of files you include in your headers. It is especially useful if your header file needs to be used by other classes/files.

However, suppose you try to forward declare classes within a given namespace:

class A::B::CClassName;
You'll probably encounter the following error message:

namespace "A::B" has no tag member named "CClassName"
There are two ways of resolving this issue:
  1. Define the namespace with the "using namespace" keyword and then declare the class:
    using namespace A::B;
    class CClassName;
    The "using namespace" keyword in the header file is generally not preffered, because it might have an adverse effect on other files—including the header file.
  2. Define the forward declaration like this:
    namespace A
      namespace B
        class CClassName;
The second method may take up more code lines, but it's a good method of forward declaration for classes with namespaces.

C.V. Ram Narayanan Sastry
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date