devxlogo

Nested Class and Forward Declarations

Nested Class and Forward Declarations

You cannot forward declare a nested class. For this reason, the following code will not compile:

   // assuming class B is nested in class A  int main()  {   class A::B; // error; cannot fwd-declare a nested class   A::B ptr; // error  }

The only way to convince the compiler to accept this code is by making the declaration of class A visible, i.e., by #including the appropriate header before main():

    // file a.h  class A  {   public:     class B {/*..*/}; // nested  };  #include "a.h"  int main()  {   class A::B; // fine but redundant   A::B ptr; // OK  }

However, once you #include the declaration of A, the forward declaration in main() becomes redundant.

Remember that nested classes are meant to hide implementation details. If you need to access a nested class anywhere outside its enclosing class, perhaps it shouldn’t be a nested class in the first place.

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