0

I saw this question on SO and wondered where this kind of code can actually be used in the real time example.

struct a
{
    static struct a b;
};


int main()
{
    a::b;

    return 0;
}

Also what is the significance of a::b; Thanks for your inputs.

Community
  • 1
  • 1
Forever Learner
  • 1,465
  • 4
  • 15
  • 30

1 Answers1

0

Such code can be used in implementation of the Singleton pattern. Here, one instance of type a is declared; if other instances are somehow forbidden, it is the singleton. In practice, however, i recall, they usually use less confusing syntax.

And, as for a::b, it does nothing useful. It just shows the name of the instance. A more useful example would be this:

struct a
{
    static struct a b;
    int data;
};

a a::b = {9};

int main()
{
    int stuff = a::b.data;
    printf("%d\n", stuff);

    return 0;
}
anatolyg
  • 26,506
  • 9
  • 60
  • 134
  • A class whose number of instances that can be instantiated is limited to one is called a singleton class. Thus, at any given time only one instance can exist, no more. We can implement that through static methods. I do not understand how making the static object of own class helps in achieving that – Forever Learner Apr 23 '12 at 17:15
  • @CppLearner The definition of `a::b` can be placed at a predefined address by the linker (this has to do with memory-mapped access to hardware) – anatolyg Apr 23 '12 at 17:22
  • Thanks, I just saw below code from [link] http://stackoverflow.com/questions/2593324/c-singleton-class which confirms your explanation. `class MySingleton { public: static MySingleton &getInstance() { static MySingleton instance; return instance; } private: MySingleton(); ~MySingleton(); };` – Forever Learner Apr 25 '12 at 17:51