Question

#include<iostream>
using namespace std;

class sample {
    public:
        static int x;
};

//int sample::x = 20;

int main() {
    sample s1;
    int sample::x = 30;
}

When i compile this program then got an error Invalid use of qualified-name 'sample::x'

I know that I am getting this error because of this statement int sample::x = 30; in main.

But i don not understand that why i can not define int sample::x = 30; in main?

Was it helpful?

Solution

As the standard says:

The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition.

Also, the definition of static data member is in the scope of a class. So,

int x = 100; //global variable

class StaticMemeberScope
{
   static int x; 
   static int y;
 };

int StaticMemeberScope::x =1;

int StaticMemeberScope::y = x + 1; // y =2 (StaticMemeberScope::x, not ::x)

OTHER TIPS

You have to allocate space for it in global namespace

#include<iostream>

class sample {
    public:
        static int x;
};

int sample::x = 20;

int main() {
    sample s1;
    sample::x = 30;
}

You can the n set it normally in main or any other method. Here is a tutorial on the static keyword. I removed the using directive because it is bad practice to bring in the whole namespace, especially when you need none of it.

The reason that static vars need to be initialized is global scope is because both static and global vars have static storage duration

You can't define a static variable within a function, but must do this outside any scope: Try

int sample::x = 30;

int main() {
    sample s1;
}

instead. You can do though:

int sample::x = 30;

int main() {
    sample s1;

    sample::x = 42; // Note the different syntax!
}

Static member are like global object can only be accessed through sample::x

You've to initialize them at global scope where class is defined.

So you can't initialize in main, that's a syntax error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top