3

Is it legal/advised to do this in C++

//Interface.h
#ifndef INTERFACE_H
#define INTERFACE_H
    #include "WinImplementation.h"
    #include "NixImplementation.h"
    class Interface {
        class WinImplementation;
        class NixImplementation;
    }
#endif

//WinImplementation.h
#ifndef WINIMPLEMENTATION_H
#define WINIMPLEMENTATION_H
    #include "Interface.h"
    class Interface::WinImplementation {}
#endif

//NixImplementation.h
#ifndef NIXIMPLEMENTATION_H
#define NIXIMPLEMENTATION_H
    #include "Interface.h"
    class Interface::NixImplementation {}
#endif
Eliezer
  • 7,209
  • 12
  • 56
  • 103
  • Whether this can work depends a lot on how you use include-guards (`#ifdef...`) – jogojapan Jan 23 '13 at 08:02
  • Oops...forgot those. I'll put them in now – Eliezer Jan 23 '13 at 08:02
  • Possible duplicate of [this](http://stackoverflow.com/questions/1021793/how-do-i-forward-declare-an-inner-class)? – Simon Jan 23 '13 at 08:03
  • they are just private in Interface? – billz Jan 23 '13 at 08:07
  • @Simon - I think my case is different because I am forward declaring them in the containing class – Eliezer Jan 23 '13 at 08:10
  • @billz - yes, Interface maintains a pointer to one of the Implementations (which it creates in its constructor) and exposes the functions in the Implementations – Eliezer Jan 23 '13 at 08:10
  • 2
    @Simon, as Elizer said, that is a good, related question, but it's not a duplicate. It's about forward-declaring a nested class directly, not about _defining_ the nested class in a different file. – jogojapan Jan 23 '13 at 08:12

1 Answers1

1

Yes, you can forward declare nested classes in C++. The following example is taken directly from the C++ standard (section 9.7.3):

class E
{
    class I1;     // forward declaration of nested class
    class I2;
    class I1 {};  // definition of nested class
};
class E::I2 {};   // definition of nested class
  • Thanks :-) now if I want `class E::I2{};` in a separate file how would I handle the recursive includes? – Eliezer Jan 23 '13 at 09:20
  • 1
    You can declare a pointer to your nested class with just a forward declaration. You can just include the correct implementation header at the bottom of Interface.h, and not include Interface.h in your implementation headers. –  Jan 23 '13 at 09:34