Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the problem with this code?

Tags:

c++

static

#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'
like image 610
Lazer Avatar asked Dec 02 '22 05:12

Lazer


1 Answers

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!

like image 172
PierreBdR Avatar answered Dec 03 '22 18:12

PierreBdR