What will happen? Here's a code that i tried, it works but i don't really get what's actually happening or how many instances of the static test t are getting created.

#include<iostream>
using namespace std;

class Test {
    public:
    static Test t;
    void hello()
    {
        cout<<"this line shall be printed";
    }
};

Test Test::t;

int main()
{
    Test a;
    a.t.t.t.hello();
    cin.get();
    return 0;
}

I'm not trying to do anything, it's just that there was a question involving whether

class test
{
static test t;
}

would get compiled or not? It got compiled and i became interested as to what's happening when we do this.

I searched for this and found a thread discussing this, however it was too complicated for me to understand.

Edited 5 Years Ago by Arkrothe: n/a

>>how many instances of the static test t are getting created.

One.

>>What will happen?

Add this to your code:

if( ( &a.t == &a.t.t ) && ( &a.t.t == &a.t.t.t.t.t.t ) )
    cout << "All test t instances are the same!" << endl;

This is just due to two things: a static data member is "globally unique" to the class; and a static member can be access either through "my_class::my_static_member" or "my_object.my_static_member". So, the a.t just accesses the static member of the class, and since a.t is also of the class "test", accessing a.t.t also accesses the same static member, and so on for a.t.t.t, ad infinitum.

The reason why it is allowed to have a static data member of the same class as the containing class is because, since it is static, it is not required to build an object of the class. By opposition, the following code will not work:

class test {
  test t;
};

This is not possible because in order to construct an object of class "test", it requires an object of class "test", this is not possible (i.e. a sort of infinite recursive paradox). So, the compiler would complain saying that "t" is an invalid data member because it is of an incomplete type. When the data member is static, then it is not required to construct an object of that class, so there is no paradox, it works and the compiler allows it because there is no reason not to.

This question has already been answered. Start a new discussion instead.