0

It's said that, Once the definition for static data member is made, user cannot redefine it. what does it exactly mean? As I am able to assign anything to it

#include<iostream.h>
class X
{
    public:
       static int i;
    X()
    {
        i = 2;    //no error in initializing it in constructor
    };
};

int X::i=1;

int main()
{
   X obj;
   cout << obj.i;   // prints 2, no prob. occur
   obj.i = 3;
   cout << obj.i;   // prints 3, same runs fine 
   X::i = 10;
   cout<<obj.i;     // prints 10, still no error
   return 0;
}

if assigning value and redefining are different, then what is redefining a static or a even a normal variable?

Thanks in advance!

  • Inside the class is the *declaration*. Outside the class is the *definition* and *initialization*. In the constructor is an *assignment*. – Some programmer dude Jun 29 '17 at 16:16
  • I don't think this is a duplicate. OP seems to be thinking that `static` and `const` are synonymous. When he said "redefine" I think he meant "assign". – Carey Gregory Jun 29 '17 at 16:22
  • Actually, I want to know what is **Redefining** a variable? and why are static variables cant be redefined –  Jun 29 '17 at 16:35
  • I echo the sentiment of @Care – Chris Parker Jun 29 '17 at 16:37
  • 1
    Previous comment got tangled up in some Javascript hell and I couldn't edit it. I echo the sentiment of Carey Gregory and Prasanna Thapa - this is a variation on that question, not a duplicate. The semantics of "static" make this worthy of a separate answer, IMHO. – Chris Parker Jun 29 '17 at 16:41

0 Answers0