CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11
  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.

  2. #2
    Join Date
    Jun 2003
    Location
    Armenia, Yerevan
    Posts
    720

    Re: Inherit from Singleton

    Well, you have not (and cannot) create any Singlton class's object explicitly, all you need is to call.
    Code:
    Singleton::Instance()->Foo();
    Thats the point.
    Next time use code-tags when posting source code.

  3. #3
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470

    Re: Inherit from Singleton

    Point 1: use CODE tags
    Point 2: Don't use leading underscore in names - the standard reserves them for compiler and standard library purposes
    Point 3: There's no need to define the copy ctor, you're disabling it.
    Point 4: You should also disable copy assign.
    Point 5: You don't need a semicolon after the closing brace of a function definition.

    On to the substance of the post...

    Point 6: Constructors can be protected.
    Point 7: Your Singleton class contains no virtual functions. what's the point of deriving from it?
    Point 8: What's going to create a Check object?
    Point 9: How are you going to use a Check object?
    Point 10: It's the singleton constructs that make a singleton. How can you make one without them?
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


  4. #4
    Join Date
    Dec 2006
    Posts
    33

    Re: Inherit from Singleton

    I think I see what you mean. You want to write a "Singleton" class where all the other singletons will derive from and then automatically become singleton.

    I'm not sure about whether static methods can be inherited in such a way. Can you try something like:

    Code:
    tempate <typename T>
    class Singleton {
    public:
        static T *instance();
    private:
        static T *instance_;
    }
    
    template <typename T>
    T *Singleton::instance() {
        return ensureInstance(); // inits instance_ if necessary
    }
    and your class would be:

    Code:
    class  MyClass : public Singleton<MyClass> { ... }

  5. #5
    Join Date
    Oct 2006
    Posts
    82

    Smile Re: Inherit from Singleton

    1 don't know what a code tag is, but I'l look it up.

    To AvDv: Yes, I was aware that could be done, but the objective was not to have to do that.

    To panzer2k4: You a right. The template approach is the solution. No literature that I have found uses inheritence to turn a normal calss into a singleton class. However, making the default constructor protected makes the compiler error go away since the compiler will code a call to the super class' constructor - now accessible to the subclass - before it codes a call to the subclass' constructor. Although the literature suggests that all constructors stay private, its of interest to experiment with the inheritance approach.

    I'm still not sure why the Instance() method is sometimes made static as well as the instance variable. I believe either one makes the instantiated object static.

    Composition doesn't make any sense here, so no point in discussing that.

    Thank you all.

  6. #6
    Join Date
    Oct 2006
    Posts
    82

    Question Purpose of code tag??

    Just out of curiousity, what's the point of code tags - beyond making things more readable?

  7. #7
    Join Date
    Dec 2006
    Posts
    33

    Re: Inherit from Singleton

    Not sure if this is your questions, but the Instance() method is made static for speed reasons - it is faster to call a static method than a class method. It is possible to have it not be staticm however the instance variable MUST be static.

    I believe with the template approach, the compiler generates a singleton for each class that subclasses the Singleton class, and hence you get a new singleton. I remember very briefly passing over this idea in a class.

  8. #8
    Join Date
    May 2005
    Location
    Oregon
    Posts
    3,725

    Re: Inherit from Singleton

    if you want to make a normal class to behave like singelton class you Simply can put a static variable inside your class .and according to variable value you can check whether to create a class or not.in constructor increment the value of variable and in destructor decrement the value of variable.

    thanx

  9. #9
    Join Date
    Oct 2006
    Posts
    82

    Smile Re: Inherit from Singleton

    To panzer2k4: Yes, your points about the need for the static variable and the speed improvement of the static method are clear, now that you mention .

    To all:

    I experimented with the idea of inheritance. Making the superclass' default constructor protected allows sublasses to instantiate the superclass via that constructor; it does not force the use of myclass::Instance() to instantiate the desired subclassed singleton.

    Actually if you try inheriting a singleton into a subclass, you'll find it makes no sense unless you re-code most of the singleton in the subclass anyway - such as hiding the default constructor. If you don't re-code, your client code can use "new" to instantiate as many subclass objects as it wants.

    Thanks for chipping in.

  10. #10
    Join Date
    Dec 2006
    Posts
    33

    Re: Inherit from Singleton

    I'm experimenting with the following solution (not sure if it's recommended):

    .h file
    Code:
    class A {
    public:
        virtual ~A() { }
        // all pure virtual functions here
        static A *getInstance();
    };
    .cpp file
    Code:
    class AImpl: public A {
    public:
        static AImpl *instance_;
    };
    
    A *A::getInstance() {
       return ensureAImpl();
    }
    That way, you completely hide the implementation from the header file: no need to define private methods, private variables, etc. If you follow this style while coding, then it is easy to stop people from instantiating directly from the header file (it is an abstract class).

  11. #11
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470

    Re: Inherit from Singleton

    Andrei Alexandrescu has a whole chapter devoted to this in Modern C++ Programming, but I'll warn you - it's pretty advanced stuff. this is not an easy task you're taking on.
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


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