Search code examples
c++singletonglobal-variables

multi file access to singleton class


I have a singleton class.

In A.h

class single
{
    public:
        static single *Instance;
        static single* getInstance()
        { if(!Instance) Instance = new single; 
          return Instance;
        }
        void hello () { cout<<"Hello"; }
    private: single(){ }
}

In A.cpp

single *single::Instance = 0;
std::auto_ptr <single> SINGLE_OBJ (single::getInstance());

In B.cpp

#include "A.h"

SINGLE_OBJ->hello();

I get the following error: SINGLE_OBJ was not declared in this scope.


Solution

  • To make SINGLE_OBJ visible in B.cpp you should declare it in A.h. i.e. :

    extern std::auto_ptr <single> SINGLE_OBJ;
    

    also, why are you using std::auto_ptr, its deprecated - you should switch to std::unique_ptr.