LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Global access in C++ (https://www.linuxquestions.org/questions/programming-9/global-access-in-c-113847/)

jpc82 11-08-2003 03:20 PM

Global access in C++
 
In my program I need to create a collection(which is a object) of objects when the program starts. I get all the data for the objects from a flat files I create when the program closes.

Now since my program will have a GUI, created with gtkmm, I need to be able to minipulate this collection. However, I don't have access to them from the widget functions.

How can I do this?

ToniT 11-15-2003 02:50 PM

I don't follow. Why don't you have access to something from some functions? From where you have the access? (Sorry for being stupid, I really have no experience on gtk-libraries; only C++ and programming in general).

MartinN 11-16-2003 11:07 AM

I think I know what you mean. This is accomplished by a pattern known as Singleton. With a singleton class you get a class that exists in exactly one instance and every component of your program can access that same object. Is this what you need? Then look at this:

The class declaration (.hh-file):
Code:

class MySingletonClass
{
public:

        // Singleton pattern
        static MySingletonClass *Instance();
       
        void AnyOtherMethod();

private:

        //Hide constructor and destructor from public
        MySingletonClass();
        ~MySingletonClass();

}; //class MySingletonClass

The class definition (.cc-file):
Code:

MySingletonClass *MySingletonClass::Instance()
{
       
        // Since the variable is static, this statement will only be
        // executed once, the first time execution reaches this point
        static MySingletonClass *sing = new MySingletonClass();

        return sing;
       
} //MySingletonClass *MySingletonClass::Instance()

Usage of the instance:
Code:

#include "MySingletonClass.hh"

// The Instance() method is static and can be accessed anywhere
// without any object reference.
MySingletonClass::Instance()->AnyOtherMethod();

Good luck with your project!
Martin

jpc82 11-16-2003 04:00 PM

Ya I think the singleton pattern is exactly what I need. As soon as I read that word I remebered it from one of my OO clases from last year, I had completly forgot about it.

Currently I have it just setup as a global variable, which I know is bad. Once I get my program a little further I'll have to start using it with the singleton pattern.


I should really setup a little web site so that I can show you guys my progress. That way you can see where all you help is creating.


All times are GMT -5. The time now is 06:34 AM.