#include<stdio.h>
class A { public: int a;};
class B: public A {
public:
static int b;
B(){
b++;
printf("B:%d\n",b);
}
};
int main() {
A* a1 = new B[100];
A* a2 = new B();
return 0;
}
Error:
In function `main':
undefined reference to `B::b'
undefined reference to `B::b'
undefined reference to `B::b'
undefined reference to `B::b'
Static variables need to be allocated outside the class. Add this line outside the class B:
int B::b;
Think of static variables as being declared with the extern
keyword. They still need to be allocated somewhere. This means the allocation should never be in the header file!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With