Global Object

I have completely forgot how to do this, or I'm thinking of another language.

How do I create in instance of an object that can be used throughout all of my .cpp files.

The class is defined in a header file so I'm just wondering if it is done through there.

IE: I have methods that use a class instance, and then in another file, more methods that use the same instance, only problem is, I cannot interface these two instances because it's two unique declarations of the same object, so pretty much, how do I have just one instance of the object that is used by all the functions, thus allowing me to interface between them.
Declare the object as extern
And instanciate it on one source file
Thanks for your help, I knew it was something like that, apparently it was.
This is called singleton pattern.
This is an example how it could be implemented:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class singleton {
public:
    static singleton& getinstance() {
        static singleton instance;
        return instance;
    }
private:
    //Don't allow copying or constructing
    singleton() {}
    singleton(const singleton&) {}
    singleton& operator=(const singleton&) {}
};

//...
singleton& s = singleton::getinstance();


EDIT: you can use extern as well. I personally prefer singleton.
Last edited on
In Java we need to put in a synchronized keyword in case the getinstance() method is called by multiple threads at the same time. So how does C++ solve this problem ?
In Java we need to put in a synchronized keyword in case the getinstance() method is called by multiple threads at the same time. So how does C++ solve this problem ?

http://lmgtfy.com/?q=java+synchronized+in+c%2B%2B
Topic archived. No new replies allowed.