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;
}

First of all, what exactly are you trying to achieve?

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.

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

Okay i get it now. Thanks for the explanation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.