-1
using namespace std;
class test{
    private:
    int a,b;
    public:
    static int count=0;
    test(int a=10,int b=10){
        count++;
    }
};
int main(){
    test t;
    cout<<t.count<<endl;
    test t1;
    cout<<t1.count<<endl;

}

I have used static member which is initialized inside the class, I have tried outside the class it works fine, but I don't get how is that a error in first place which is initializing the member inside class.

When I run the above code it gives me the following error: ISO C++ forbids in-class initialization of non-const static member 'test::count'.

Why I cant initialize a static member inside class?

amitabha
  • 11
  • 3
  • Isn't the error message clear enough? Just initialise it outside the class. The reason is probably to be consistent with the way that global variables are declared and defined. You initialise a global variable at it's definition not at it's declaration. – john Jul 19 '22 at 07:18
  • Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) and a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). There are plenty of dupes for this. The first step is to do "search and then research" as explained in [how to ask](https://stackoverflow.com/help/how-to-ask). Moreover, this is explained in any beginner level C++ book. – Jason Jul 19 '22 at 07:33

1 Answers1

4

The error is quite clear, you can't initialize the variables when you declare them.

Instead declare them like normal (without initialization) and then remember to add their definitions outside of the class, with the actual initialization:

class test{
    private:
    int a,b;
    public:
    static int count;
    test(int a=10,int b=10){
        count++;
    }
};
int test::count=0;

From the C++17 standard inline definition and initialization of static member variables was added:

class test{
    private:
    int a,b;
    public:
    inline static int count=0;  // Note the inline keyword
    test(int a=10,int b=10){
        count++;
    }
};
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621