Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: All
Dec 3, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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
     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.

Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date