13

I make the following declarations:

class Servo {

protected:

    static const int maxServos = 16;    
    static Servo servos[maxServos]; //Array declaration
};

Servo Servo::servos[Servo::maxServos]; //Array definition

...and it compiles, which is great ! But I don't understand why it compiles because it seems to me that maxServos is protected and I am using it in a global scope when I define the array. I tried using it in another global context and indeed I did get a compile error:

int main() {
    std::cout << Servo::maxServos;  //This will not compile.
}

So what is going on ? Is the whole definition of the array somehow scoped by the namespace qualifying the array ? Is it a compiler glitch ?

I am using g++ -std::c++11 on a Raspberry PI using Lubuntu 16.04 O/S.

curiousguy
  • 8,038
  • 2
  • 40
  • 58
user1759557
  • 445
  • 4
  • 12

1 Answers1

20

This definition

Servo Servo::servos[Servo::maxServos]; //Array definition

is not global scope, it's class scope due to the (first) Servo:: scope qualifier. You can make this even clearer by removing the redundant second scope qualifier:

Servo Servo::servos[maxServos]; //Array definition

and it still compiles just fine.

TL;DR -- the scope qualifier on the declarator makes everything after in the same declarator in that scope.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • 1
    "_everything after in the same declarator in that scope_" what about `C::mem_type C::static_obj;`? Is `C::mem_type` morally after `C::static_obj`? – curiousguy Apr 08 '19 at 23:49
  • 2
    @curiousguy: `C::mem_type` is a declaration specifier and not part of the declarator at all. Its also physically before the declarator, so could not be easily parsed otherwise (morality doesn't enter into it). – Chris Dodd Apr 09 '19 at 20:21
  • I didn't make myself clear. The Q was about access control to protected names. "Should access control be done as from a member, incl. for `C::mem_type` in `C::mem_type C::static_obj`?" was the precision I asked. – curiousguy Apr 10 '19 at 00:45
  • I think I have just had to completely update the way I view the scope of namespace qualifiers in expressions. I have been imagining it working another way for years (just affecting the symbol which is qualified). Thanks for your insight. – user1759557 Apr 15 '19 at 02:18