griffintaur
griffintaur

Reputation: 87

Static object declaration only causing no error

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

Answers (2)

Barry
Barry

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

VP.
VP.

Reputation: 16705

  1. 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

  2. If you will try to initialize a non-static class member by static one, here is the same behaviour:

    1. If you define your static member here is no error.
    2. 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

Related Questions