1

Can a namespace be nested in a class in C++?

Here is what I get with gcc-11.2.0:

struct C1 {}; // works 
namespace N1 {const int a = 888;} // works

struct C2 { namespace N2 {const int a = 888;} };
// error: expected unqualified-id before ‘namespace’

Namespaces can be nested, so why can't one nest a namespace in a class (which is also a kind of a namespace)?

digito_evo
  • 3,216
  • 2
  • 14
  • 42
S.V
  • 2,149
  • 2
  • 18
  • 41
  • Logically, it is because the standard requires a class to have exactly one declarative region (i.e. once a class definition is closed with the `}`, it can't be opened up and more members or type declarations added to it) but a namespace can have multiple declarative regions. The difference is important for encapsulation using classes (e.g. once a class is defined, other code cannot come along and sneakily add new member functions to the class). Placing a namespace in a class would break the requirement that it have only only one declarative region. – Peter Jan 15 '22 at 00:47

0 Answers0