|
-
Mar 23rd, 2002, 10:35 PM
#1
C++ Classes constructor
If i have a class name Class. The the function "Class" is called for every instance of the class when it starts, and "~Class" is class is called for every instance when it exits. My question is, is there a function that gets called only once when it starts, no matter how many instances of the class?
I ask this because im making a window into a class and in the constuctor i register the window class. I figure this might cause problems if theres more than one instance of the class. Or its just kind of a waste to register the window more than once.
-
Mar 24th, 2002, 04:49 AM
#2
Fanatic Member
You can use a static variable as a counter in your class. If it's 0, then you register the class, and if it's larger than 0, then you won't.
Don't forget to increment or decrement it every time a new instance is created or destroyed, so you're able to deregister the class if it's necessary, when the counter is 0.
-
Mar 24th, 2002, 07:00 AM
#3
Monday Morning Lunatic
Re: C++ Classes constructor
Originally posted by ChimpFace9000
If i have a class name Class. The the function "Class" is called for every instance of the class when it starts, and "~Class" is class is called for every instance when it exits. My question is, is there a function that gets called only once when it starts, no matter how many instances of the class?
I ask this because im making a window into a class and in the constuctor i register the window class. I figure this might cause problems if theres more than one instance of the class. Or its just kind of a waste to register the window more than once.
The Singleton pattern might help you here. The idea is that you have a private constructor, and you request the object which is created statically:
Code:
class Singleton {
public:
inline Singleton& instance() {
static Singleton myself;
return myself;
}
private:
inline Singleton() { }
};
...is this the sort of thing you need?
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Mar 24th, 2002, 10:19 AM
#4
parksie: Im not sure what you mean.
riis: PERFECT!!! Its so simple, i cant believe i didnt think of that.
-
Mar 24th, 2002, 10:21 AM
#5
Monday Morning Lunatic
It means you'll only ever have one "instance" of that class.
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|