Reputation: 87
Why the code is not causing compile error?
#include<iostream>
class x{
private:
int v;
public:
x():v(7){};
};
class b{
private:
static x as;
int a;
public:
b():a(8){};
};
//x b::as;
int main(){
b g;
return 0;
}
Even after commenting the particular line x b::as
code works which I think it should as I haven't define/initiate my static object which is necessary. Why is it so?
And what if I initiate non-static object using static object like static x asd; x bv=asd;
?
Upvotes: 1
Views: 63
Reputation: 302852
The program compiles and runs fine because it doesn't actually violate any rules. The key rule here is, in [basic.def.odr]:
Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required.
In your program, b::as
is not odr-used yet. However, as soon as you use it somewhere (maybe you take its address, or try to access as.v
, etc), then you violate this condition because you didn't provide a definition for as
.
Upvotes: 2
Reputation: 16705
It wil not ever cause a error until you use it (b::as
) in your code. Then, linker will not able to find it's definition and cause a unresolved reference error:
undefined reference to b::as
If you will try to initialize a non-static class member by static one, here is the same behaviour:
If you don't do that, there would be a unresolved reference error.
class b {
private:
static x as;
int a = b::as;
public:
b():a(8){};
};
x b::as; // this is now correct but if you comment this, you should can't initialize `b::a` with `b::as` then because it will cause a unresolved reference error.
Upvotes: 1