0

I was learning static data members in c++ and I wrote this code but on compilation, it is giving me this error:

main.cpp:21:12: error: ‘int Test1::a’ is private within this context

 Test1::a=50;
        ^

main.cpp:17:5: note: declared private here int Test1::a;

But I don't know why this error is coming and how to solve this.

#include <iostream>
using namespace std;

class Test1{
    static int a; //declaration
};
int Test1::a; // definition

int main()
{
    Test1::a=50;
    cout<<"a= "<<Test1::a<<endl;
}
3
  • 6
    static is a red herring. Unless specified explicitly, everything in a class is private by default. static has nothing to do with it. Commented Aug 25, 2021 at 10:49
  • 1
    @tobias: Alas incorrect on both counts. 1) It is a definition, 2) You can in some circumstances, e.g. access checks are not made with template specialisations. The second point comes in handy when writing unit tests.
    – Bathsheba
    Commented Aug 25, 2021 at 11:05
  • 1
    Fair enough, removed my incorrect comment. Thank you
    – tobias
    Commented Aug 25, 2021 at 15:54

1 Answer 1

3

You declared static int a as private member in the class, which can be accessed only within class. Class members are private by default. You should have declared it as public.

class Test1{
public:
    static int a; //declaration
};
int Test1::a=0;
.
.
.
.
//whatever
2
  • As we know the value of static data members, once initialized cannot be changed, but if I declare this in public, I am able to change the value.
    – Ritisha
    Commented Aug 27, 2021 at 19:07
  • The value of static data member cannot be changed only if it declared as const. Commented Aug 27, 2021 at 21:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.