Static questions

Hi, I was trying some class features such as static members(data members or member functions), and found that static member can have incomplete type. I wonder: When does static object created? at compile time? If an ordinary object such as t3(below) is created at runtime, the compiler should have already known the definition of Test at compile time. I'm confused. pls help

1
2
3
4
class Test {
    static Test t1;   //Ok
    Test t3;          //error, cause Test's definition was not complete
};
this is because line 2 doesn't actually define t1.

you will still need to add Test Test::t1; to your cpp file.
Last edited on
oh, like other static members defined outside the class? thanks.
1
2
3
4
class Test {
    static Test t1;   //Ok
    Test t3;          //error, cause Test's definition was not complete
};

The compiler needs to know the size of each data member when you declare the class. Otherwise it doesn't know how to lay it out in memory. To see why this example doesn't work, consider what would happen if it did. For demonstration let's add one more member:
1
2
3
4
5
class Test {
    static Test t1;   //Ok
    Test t3;          //error, cause Test's definition was not complete
    int i;
};


Now let's write some code:

1
2
3
4
5
Test myTest;
myTest.i = 2;
myTest.t3.i = 3;
myTest.t3.t3.i = 4;
myTest.t3.t3.t3.t3.t3.t3.t3.t3.t3.t3.t3.t3.t3.t3.t3.t3.t3.t3.t3.t3.i = 5;  // Hmmm.... 

And it theory you should be able to do this all day. Each Test object contains an instance of itself, and that one contains an instance, and that one does too, and on and on until memory runs out.

Great, like recursive functions. But it is said we can define pointers of class itself such as
1
2
3
4
5
class Test {
    static Test t1;   //Ok
    Test *t2;         //OK
    Test t3;          //error, cause Test's definition was not complete
};

Does t2 have any useful instance? or the static t1 got any practical one? thanks.
Last edited on
yes, if Test was an element in a linked list, t2 could well point to the next item in the list.

yes again, if Test::t1 were a master object that all instances took some data from during initialisation for example. I dont think any experienced c++er would use that mechanism mind. but it is possible.

Its worth noting that dhayden's example of t3.t3.t3.t3 etc wouldn't get to execute because memory overflow would occur at line 1 of his/her example, as it recursively allocated a new t1 for each Test instance.
Does make sense, thanks. I'll try some examples.
Topic archived. No new replies allowed.