user3160866
user3160866

Reputation: 387

class have an object of selftype

Want to understand why there is no compilation error

If a class has a static object of same type and the class has parametric constructor why it didnt enfore while creating it

class test {

      static test a;
      int b;

      public:
            test(int arg) {
                 b = arg;
              }
};

int main() {
  test t1(100);

  return 0;

}

I know that to make it work I need to add as

 test test::a(100)

but without the above line why there is no compilation error . Any pointer

Upvotes: 3

Views: 60

Answers (1)

Aconcagua
Aconcagua

Reputation: 25516

If at all, it would be a linker error. But as you don't use the static object, the linker won't look for it and thus no build error...

Try this for comparison:

int main()
{
    test::a.b = 7; // sure, you need to make the members public for...    
    return 0;
}

Now you do use the static object – but it wasn't created anywhere and the linker will fail to look it up.

Upvotes: 6

Related Questions