Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this static const int member variable appear to be accessible publicly in array definition?

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.

like image 314
user1759557 Avatar asked Apr 08 '19 16:04

user1759557


1 Answers

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.

like image 135
Chris Dodd Avatar answered Nov 15 '22 20:11

Chris Dodd