467,858 Members | 1,454 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,858 developers. It's quick & easy.

A question regarding to the keyword static

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.

Mar 22 '07 #1
  • viewed: 1392
Share:
1 Reply

wizwx schrieb:
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.

Mar 22 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

9 posts views Thread by Bryan Parkoff | last post: by
5 posts views Thread by siliconwafer | last post: by
16 posts views Thread by vaughn | last post: by
14 posts views Thread by Zeng | last post: by
3 posts views Thread by Danny Din | last post: by
54 posts views Thread by Sahil Malik [MVP] | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.