A question regarding to the keyword static

W

wizwx

I just noticed an interesting implementation of Singleton from Bruce
Eckel's "Thinking in C++" vol. 2, pp 620:
class Singleton {
static Singleton s;
public:
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.
 
A

Alexander Block

wizwx said:
I just noticed an interesting implementation of Singleton from Bruce
Eckel's "Thinking in C++" vol. 2, pp 620:
class Singleton {
static Singleton s;
public:
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.

A static class is only instanciated once. A normal member would result
a infinite class size and recursive constructor call.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top