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