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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: