F
F
Flaker2014-01-01 22:46:50
C++ / C#
Flaker, 2014-01-01 22:46:50

(C++) An inherited Singleton class. How to implement?

Is it possible to implement an inherited Singleton class? And how to do it?
That is, if there is a CSingleton class that implements the Singleton pattern. We inherit the CSingleChild
class from CSingleton . Now the CSingleChild class object will be created once. PS It is possible without thread-save. On the example of Myers.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Trrrrr, 2014-01-02
@Flaker

one of the options through templates:
Something like:

#include <iostream>
template <class T> class Singleton 
{
protected:
  Singleton(){};
  Singleton(const Singleton&);

public:
  static T& GetInstance()
  {
    static T instance;

    return instance;
  }
};

class AnotherSingleton : public Singleton<AnotherSingleton>
{
private:
  int i;

public:
  void SomeFunc()
  {
    i = 10;
    std::cout<< i;
  }
};
 
int _tmain(int argc, _TCHAR* argv[])
{
  AnotherSingleton::GetInstance().SomeFunc();
  return 0;
}

This is sample code, it can be improved.
By the way, in C++11 such code will already be a safe thread.
In fact, such a class can be improved very well, but it will do for an example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question