1

Here is some code:

class aclass {
  int x = 1; 
  static float peanut; //definition not allowed here or in any other class
};

float aclass::peanut = 5.2; //definition seems to only be allowed at file scope

int main() {
  //definition of peanut not allowed here
  return 0;
}

So why is peanut not allowed to be defined inside a block, such as functions or classes?

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
  • 2
    Static variables can be declared in a function – NathanOliver Jun 29 '17 at 20:15
  • @NathanOliver well I fell a little embarrased for not double checking then.. But can they be declared in functions when they cannot be declared in classes then? –  Jun 29 '17 at 20:23
  • Read the Q&A this is closed to. It will tell you why it is needed for classes. – NathanOliver Jun 29 '17 at 20:48
  • @NeiLee -- nothing to be embarrassed about. You're right: static members of classes **cannot** be defined inside a block. Static variables defined inside functions belong to the function and can't be used outside of it. They're a completely different kind of animal. – Pete Becker Jun 29 '17 at 21:08
  • @PeteBecker thanks kind man :-) So now I understand that static members need to be defined outside a block because of the "one definition rule" but I do not completely get what you mean. "Static variables defined inside functions belong to the function" yes but aren't you talking about variables that are not class members, like "static int hey = 2;" instead of "float aclass::peanut = 5;? Would both "hey" and "aclass::peanut" belong to the function they are defined in? :-/ –  Jun 29 '17 at 21:41
  • 1
    @NeiLee - right: static variables that are defined inside a function are not class members. – Pete Becker Jun 29 '17 at 22:06
  • @PeteBecker hmm when I try to define `aclass::peanut` in `main()`, it says "member cannot be defined in current scope?" So can you really define static member variables inside functions? –  Jun 30 '17 at 09:21
  • @NeiLee -- no, you cannot define static **member**variables inside functions. You can define ordinary variables: `void f() { static int counter = 0; std::cout << counter << '\n'; } int main() { for (int i = 0; i < 10; ++i) f(); return 0; }` – Pete Becker Jun 30 '17 at 12:14

0 Answers0