2

Why does class support the initialization of the static variable inside the
class with const keyword and without const keyword why does not allow to
initialize the static variable inside the class

class test  
{  
public:  
 int x;  

 static int y = 2; // It will throw an error  
 static const int z = 3; // It will not throw an error, why?  
};  

int main()  
{  
   return 0;  
}  
Yogendra Kumar
  • 113
  • 1
  • 8
  • 1
    Use dot and commas, question is hard to understand – Jacek Cz Sep 06 '17 at 17:46
  • It is to ease linker and the ODR. where would be the definition of `test::y` ? – Jarod42 Sep 06 '17 at 17:49
  • You can't declare non-const in definition, only define it. And then you must declare it outside class in cpp file – Dan Sep 06 '17 at 18:01
  • Possible duplicate of [Defining static const integer members in class definition](https://stackoverflow.com/questions/3025997/defining-static-const-integer-members-in-class-definition) – Dan Sep 06 '17 at 18:04
  • "The static keyword is only used with the declaration of a static member, inside the class definition, but not with the definition of that static member": http://en.cppreference.com/w/cpp/language/static – Dan Sep 06 '17 at 18:06
  • 1
    Because they are declarations, not definitions. `static const int` and other integral types are special cases – Passer By Sep 06 '17 at 18:06
  • 1
    See also https://stackoverflow.com/a/185848/868044 – Dan Sep 06 '17 at 18:07
  • 2
    Possible duplicate of [Initializing private static members](https://stackoverflow.com/questions/185844/initializing-private-static-members) – Rotem Sep 06 '17 at 18:14

0 Answers0