Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static class object

Tags:

c++

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;
}
like image 551
Utkarsh Srivastav Avatar asked Feb 21 '23 16:02

Utkarsh Srivastav


2 Answers

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()
{
  ...
like image 68
NPE Avatar answered Mar 07 '23 10:03

NPE


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.

like image 34
cha0site Avatar answered Mar 07 '23 10:03

cha0site