I just read this answer and it completely puzzles me.
I always thought that a class declaration could appear many times, and only a definition should exist only once, for example:
/*class Class {*/ class A; // (1) forward declaration class A { // (2) definition, only once int m; }; class A; // (3) declaration again, legal? class A a; // (4) declaration again, legal? /*};*/
From a related answer: (3) (and (4)?) Is illegal if the above code is nested inside a class (the definition and class A declarations are nested inside class Class ).
In cppreference, I found the example above, not nested :
struct s { int a; }; struct s; // does nothing (s already defined in this scope) void g() { struct s; // forward declaration of a new, local struct "s" // this hides global struct s until the end of this block s* p; // pointer to local struct s struct s { char* p; }; // definitions of the local struct s }
See the second line.
Question: Given that it is illegal inside the class, is this my sample code and the cppreference example above is legal if it is not nested inside the class? Or in a more general sense: when a class declaration can follow a definition (how does this happen in namespaces, for example)? If this is legal, why is there a difference?
alain source share