devxlogo

Forward Declaration of Classes Within Namespaces

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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist