[prev in list] [next in list] [prev in thread] [next in thread] 

List:       kde-devel
Subject:    Re: static class in c++
From:       John Gluck <john.gluck () sympatico ! ca>
Date:       2001-04-24 0:36:05
[Download RAW message or body]

Hi Greg

If I understand this correctly, you are trying to make a class of which there can
only be one instance. This is sometimes called a singleton.

If that's so, one way to do it is create a private static member in the class and
check the value. If it's zero, then you can create the class and set the value to
something else. If it's non-zero, then the class has been instantiated and you don't
do it again.

There may well be better ways of doing this but I don't know what they are...

John

Greg Hulands wrote:

> I am relatively new to c++ and my reference book does not seem to cover this
> topic.
>
> I have a class Foo() but want to make it only to be instaniated once, so when
> a new call to the class is made it returns the same object. So in the
> implementation of Foo I have at the top of the file
>
> static Foo *foo = 0;
>
> In the constructor I then have
>
> Foo()
> {
>         if (!foo)
>                 foo = new Foo;
>
>         return foo;
> }
>
> but this just makes a recursive call to the constructor as it has not
> allocated space for the object. What memory allocation do i use in the
> constuctor?
>
> Greg
>
> >> Visit http://master.kde.org/mailman/listinfo/kde-devel#unsub to unsubscribe <<

 
>> Visit http://master.kde.org/mailman/listinfo/kde-devel#unsub to unsubscribe <<

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic