Compiler error when a static member of a class is private

In the following code, I set a static variable of a class is private. Then I initialize its value as for a public static member of a class. However, a compiler error has been occurred. Please help me clarify this issue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  #include <iostream>
using namespace std;
class A{
private:
    static int num;
public:
    A(){
    cout <<"A new object of the class has been created!"<<endl;
    num++;
    }
};
int A::num=0;
int main(){
    A a_1;
    A a_2;
    cout<<A::num<<endl;
}


The message after compiling:
||=== Build: Debug in class (compiler: GNU GCC Compiler) ===|
D:\C++\Learning\project\class\main.cpp||In function 'int main()':|
D:\C++\Learning\project\class\main.cpp|12|error: 'int A::num' is private|
D:\C++\Learning\project\class\main.cpp|16|error: within this context|

||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
Last edited on
a private class can only be used by member functions

a public one can be used by all functions

hope that helps
The operation in Line 12 is just initialization of a static variable "num". I think I would be ok even with a private variable.
Line 12 is fine. The problem is when you try to access the private variable from main(). If you want to provide read-only access to functions outside the class you could create static getter function.

1
2
3
4
5
// in the public area of class A
static int getNum() { return num; }

// in function main()
cout << A::getNum() << endl;
Last edited on
Topic archived. No new replies allowed.