CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11

Threaded View

  1. #1
    Join Date
    Oct 2006
    Posts
    82

    Smile Inherit from Singleton

    I need a bit of help with the use of the Singleton pattern. The classic code is shown below and I understand it well.

    What I don't understand is how to turn a normal class into a singleton class without coding all the singleton constructs.

    The code below, of course, generates the following compiler error because the Singleton's constructors are all private. But what is the proper class code for constructors if the Singleton constructors are all left private?

    Compiler error: d:\visual studio express\visual studio 2005\projects\singletontest1\singletontest1\check.cpp(2) : error C2248:
    'Singleton::Singleton' : cannot access private member declared in class 'Singleton'

    ---------------------------------------------
    In the Singleton.h file:
    ---
    Code:
    class Singleton
    {
    public: 
        static Singleton* Instance();
    private:
    	Singleton();
    	Singleton(const Singleton&);
       	static Singleton* _instance;
    };
    -----
    and the Singleton.cpp file:
    -----
    Code:
    #include "Singleton.h"
    Singleton* Singleton::_instance = 0;
    
    Singleton::Singleton(){};
    Singleton::Singleton(const Singleton&){};
    
    Singleton* Singleton::Instance() {
        if (_instance == 0) {
            _instance = new Singleton;
        }
        return _instance;
    }
    ------------------------------------------------
    And the check.h file:
    ----
    Code:
    #include "singleton.h"
    
    class Check : public Singleton
    {
    public:
    	Check(void);
    };
    --------
    The Check.cpp file:
    -------
    Code:
    #include "Check.h"
    Check::Check(){};
    ------------------------------
    Last edited by Lou Arnold; December 20th, 2006 at 10:25 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured