anilLuwang
anilLuwang

Reputation: 25

static variable declaration and definition in C++

I have a sample code as shown below:

 class myclass
{
public:
    static int j;
    myclass(){};
    ~myclass(){};
};

int main(int argc, char** argv) {
    myclass obj;
    return EXIT_SUCCESS;
}

Now I have declared a static int inside myclass and although I have not defined it, the compiler does not give me any errors until I began using the static variable. Why is that?

Upvotes: 0

Views: 74

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

"the compiler does not give me any errors until I began using the static variable. Why is that?"

Because it didn't need to be linked with your code until that point (when you start to use it). Unused code is ignored / stripped off by the linker.

Upvotes: 2

dom0
dom0

Reputation: 7486

Because these are linker errors, not compiler errors. Linker errors never arise until you use an undefined symbol.

Upvotes: 2

Related Questions