Static object member of the same class

Jun 21, 2015 at 11:16am
Why is this code legal in C++?

1
2
3
4
5
6
7
class myClass
{
public:
	int someInt;

	static myClass subObject; // infinite loop?
};


Wouldn't it cause an infinite loop of object creation? I mean, when you declare a myClass object, it would create a static myClass object, which would create a static myClass object, which would...etc?

And how could code like this be useful in real world coding?
Jun 21, 2015 at 12:35pm
"static" attributes and methods aren't part of an object. Think of them as class attributes. They will not be instantiated on object creation. So they exists only once while non-static attributes do exist as a separate instance for each object.

"static" attributes are helpful f.e. to realize singletons, to define constants or initialization purposes.
Jun 22, 2015 at 8:31am
Ah. It's all clear now. Thank you :)
Topic archived. No new replies allowed.