2

I have a class whose declaration is getting too bloated for a single header file. I nest classes and structures within it to reinforce their relationship together, so I'd like to keep them together (in the sense that I must use the outermost class's namespace to use the classes within)

Is there a way to declare nested classes from another header file? Or perhaps at least declare the methods of the nested class in another header file? (many methods per class is the reason for the bloat, the number of classes is relatively reasonable at 10)

The structure looks a bit like this:

class Stage{
    class Quad{
        Quad();
        Quad(int width, int height);
        // like 20 different constructors, plus methods
    private: 
        glm::vec3 p[4];
    };
    class Line{
         // ...
    };
    // and a bunch of other classes

    // Stage methods
    void draw(Quad quad);
    void draw(Line line);
    // ...
};

I should probably add, I can't expand them inline with the preprocessor, since that messes up my IDE's code completion if I get creative with it.

Anne Quinn
  • 12,609
  • 8
  • 54
  • 101
  • There's [c++ - How do I forward declare an inner class? - Stack Overflow](https://stackoverflow.com/questions/1021793/how-do-i-forward-declare-an-inner-class) which is what the answer below is doing -- but it won't achieve what you want to with separating into multiple header files anyway? – user202729 Feb 06 '21 at 09:05

1 Answers1

3

Is there a way to declare nested classes from another header file?

No, nested classes can only be declared in their surrounding class definition.

Or perhaps at least declare the methods of the nested class in another header file?

Yes, you can just declare the nested classes within their class, then define them later.

class Stage{
    class Quad;
    class Line;
    // and a bunch of other classes

    // Stage methods
    void draw(Quad quad);
    void draw(Line line);
    // ...
};

// ... later
class Stage::Quad {
    // stuff
};

// ... later still
class Stage::Line {
    // whatever
};
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644