Static Attribute in Class

1
2
3
4
5
class xyz
{
public: 
   static int abc;
}obj1,obj2;

Are static attributes allowed in a Class?

How can this work? As far as I know, only when we instantiate the class(create an object), then memory is allocated, but keyword 'static' needs to allocate memory instantly. I fear that every new object of this class type created will access a 'common' variable abc, like for example below:-
1
2
obj1.abc = 1;
obj2.abc = 2;

Result:- Both obj1.abc and obj2.abc will contain value 2. Is this interpretation correct?

Please help!
Correct. The correct syntax is:
1
2
obj1::abc = 1;
obj2::abc = 2;


Static members have global lifetime(are initialised as program start and last while the program runs), and class scope (only accessible via the class).
Last edited on
Thanks!
Topic archived. No new replies allowed.