Why are static class objects allowed in C++? what is their use?
#include<iostream>
using namespace std;
class Test {
static Test self; // works fine
/* other stuff in class*/
};
int main()
{
Test t;
getchar();
return 0;
}
This just works; the compiler doesn't have to do anything special simply because self
is both a static member of Test
and is of type Test
. I see no reason why this special case would need to be specifically prohibited.
Now, there is a problem with Test::self
in that you declare the variable, but fail to define it. However, this is simply a bug in your code and is easily fixed:
class Test {
...
};
Test Test::self; // <--- the definition
int main()
{
...
You use it for things that are shared between all instances of the class. For example, you can use it to implement the Singleton pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With