0

Might be a dumb question. My apologies, but I would like to do the below,

connectionState currentState;

class connectionState {
    public:
        .......
        .......
};

rather

class connectionState {
    public:
        .......
        .......
};

connectionState currentState;

The former doesn't compiles at all while the latter does. So, no way to do this?

jeffbRTC
  • 1,941
  • 10
  • 29
  • 1
    You can do that with pointers and forward declaration. But, with objects, it needs the full class definition prior to instantiating. – ChrisMM Jan 10 '21 at 12:59
  • No way. What problem do you have that you think this will solve? – StoryTeller - Unslander Monica Jan 10 '21 at 12:59
  • @StoryTeller-UnslanderMonica I know my example is not enough to display what it actually solves. But I believe in my case, It's good for my eyes at least because I can see all globally declared ones on top of file rather at random places. – jeffbRTC Jan 10 '21 at 13:00
  • @ChrisMM Thanks for introducing me into forward declaration. Found a similar question, https://stackoverflow.com/questions/9119236/c-class-forward-declaration – jeffbRTC Jan 10 '21 at 13:04

1 Answers1

0

There are forward declarations for this. Forward declarations also resolve the problem of circular dependencies:

class connectionState; // forward class declaration
extern connectionState currentState; // forward global extern variable declaration, now possible because connectionState is declared as a typename/class name
static connectionState currentState; // forward global static variable declaration 

class connectionState { ... }; // implementation/definition, can access currentState
connectionState currentState = ...; // definition/initialization
connectionState currentState {...}; // definition/initialization
cmdLP
  • 1,658
  • 9
  • 19
  • You would need `extern connectionState currentState;` to make it a forward declaration (currently this is a definition and does not compile) – Artyer Jan 10 '21 at 21:47
  • Not to forget: `static` and `inline`, etc... variables – cmdLP Jan 10 '21 at 21:50