Reputation: 1721
find a bug in following code :
class A
{
public:
static int i;
void print()
{
cout<< i << endl ;
}
};
int main()
{
A a;
a.print();
}
I run above code, and I am getting "undefined reference to `A::i'" . Why I am getting this error ?
Upvotes: 4
Views: 2049
Reputation: 262919
Since A::i
is a static
member, it has to be defined outside of the class:
using namespace std;
class A
{
public:
static int i; // A::i is declared here.
void print()
{
cout << i << endl;
}
};
int A::i = 42; // A::i is defined here.
Upvotes: 12
Reputation: 73433
The static int i
in the class A
is just a declaration, you need to define it outside the class by adding a statement int A::i = 0;
Upvotes: 7