What is the problem with this code?

c++, static

Solution

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!

Problem

``` #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' ```

Original source