A question regarding to the keyword static

Discussion in 'C++' started by wizwx, Mar 22, 2007.

  1. wizwx

    wizwx Guest

    I just noticed an interesting implementation of Singleton from Bruce
    Eckel's "Thinking in C++" vol. 2, pp 620:
    class Singleton {
    static Singleton s;
    static Singleton& instance() {
    return s;
    // ....
    Singleton Singleton::s;

    It is interesting to note that a static member of itself (Singleton)
    is declared inside the Singleton class. I tested the code in linux,
    and g++ compiled it successfully.

    My question is: How could this happen? How could a class ever have a
    member of the type of itself? This is obviously invalid if there is no
    keyword static. However, what features of the keyword "static" make
    this feasible?

    Thanks for any comments or inputs.
    wizwx, Mar 22, 2007
    1. Advertisements

  2. A static class is only instanciated once. A normal member would result
    a infinite class size and recursive constructor call.
    Alexander Block, Mar 22, 2007
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.