Can a singleton class be inherited.
if yes,
then how can we do it?
**EDIT:***I mean to say that if we have a class which uses singleton design pattern,then can it be inherited?*
singleton has private constructor so inheritance is not possible. besides singleton has static methods to instantiate private instance member and since you can't override static methods it would be pointless to inherit from singleton.
It depends on how is your implementation for the design pattern. The simplest form is to make a class like this:
class MySingleton
{
public:
static MySingleton &getInstance()
{
static MySingleton instance;
return instance;
}
private:
MySingleton();
~MySingleton();
};
In this case, it can't be inherited because the derived class has no access to its constructor. You could make the constructor protected, but this will enable other derived classes to be non-singleton at will, which can be messy from a design perspective. But usually this simple form is not the preferred way to implement singletons since you have not much control about its lifetime and it's difficult to properly handle dependencies between singletons - not to mention possible multithreading issues. The book Modern C++ Design (http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315/ref=sr_1_1?ie=UTF8&s=books&qid=1270652521), among others, has better implementations; they are template-based and the template instantiation is what makes the object a singleton (and its parameter is the class that will be made singleton). This makes easier to do what you want, since the 'singleton-ness' is detached from the class itself. But nonetheless I think you'd need some policy (possibly enforced by code) to avoid that some class derived from a singleton would be non-singleton, which is difficult to implement.
My recommendation would be to have abstract base classes as ancestors for your singletons, and put the commom behaviour in them, not in the singleton itself, and have the singleton always as the 'final' class (borrowing this meaning from Java).
Singleton classes are meant to be inherited. The singleton pattern isn't of much value without inheritance.
Define a mostly abstract base class with a static instance() member function.
Define one or more derived classes that implement the base interface.
Implement instance() to decide at runtime which class to instantiate and return.
I have a Singleton class that I inherit from in many instances.
Here is the Singleton:
template <class Target>
class Singleton_Shared_Ptr
{
//---------------------------------------------------------------------
// Public Constructors & Destructors
//---------------------------------------------------------------------
public:
//! Destructor.
virtual ~Singleton_Shared_Ptr();
//---------------------------------------------------------------------
// Public methods
//---------------------------------------------------------------------
public:
//! Returns a pointer to the instance.
static boost::shared_ptr<Target> ptr(void);
//! Returns a reference to the instance.
static Target & ref(void);
//---------------------------------------------------------------------
// Protected methods
//---------------------------------------------------------------------
protected:
//! Default constructor.
Singleton_Shared_Ptr();
//---------------------------------------------------------------------
// Private methods
//---------------------------------------------------------------------
private:
//! Copy constructor, not implemented.
/*! The copy constructor is declared so that the compiler will not
* automatically generate one.
*/
Singleton_Shared_Ptr(const Singleton_Shared_Ptr& s);
//! Assignment operator, declared but not defined.
/*! The assignment operator is declared so that the compiler will not
* automatically generate one.
*/
Singleton_Shared_Ptr& operator=(const Singleton_Shared_Ptr& s);
//---------------------------------------------------------------------
// Private members
//---------------------------------------------------------------------
private:
static wxMutex m_instance_mutex;
};
template<class Target>
wxMutex Singleton_Shared_Ptr<Target>::m_instance_mutex;
//-------------------------------------------------------------------------
// Singleton_Shared_Ptr Constructors & Destructors
//-------------------------------------------------------------------------
template <class Target>
inline
Singleton_Shared_Ptr<Target> ::
Singleton_Shared_Ptr()
{
}
template <class Target>
inline
Singleton_Shared_Ptr<Target> ::
~Singleton_Shared_Ptr()
{
}
//-------------------------------------------------------------------------
// Singleton_Shared_Ptr methods in alphabetical order
//-------------------------------------------------------------------------
template <class Target>
boost::shared_ptr<Target>
Singleton_Shared_Ptr<Target> ::
ptr(void)
{
static boost::shared_ptr<Target> p_instance;
if (p_instance.get() == NULL)
{
wxMutexLocker lock(m_instance_mutex);
if (!p_instance)
{
p_instance.reset(new Target);
}
}
return p_instance;
}
template <class Target>
Target &
Singleton_Shared_Ptr<Target> ::
ref(void)
{
return *(ptr());
}
Here is the usage of the singleton:
class Manager
: public Singleton_Shared_Ptr<Manager>
{
//---------------------------------------------------------------------
// Friends
//---------------------------------------------------------------------
friend class Common::Singleton_Shared_Ptr<Manager>;
//---------------------------------------------------------------------
// Public Constructors and Destructors
//---------------------------------------------------------------------
public:
//! destructor
virtual ~Manager();
//---------------------------------------------------------------------
// Protected Methods
//---------------------------------------------------------------------
protected:
//! Constructor
Manager();
//! Copy constructor -- declared but not implemented.
Manager(const Manager& m);
//! Assignment operator -- declared but not implemented.
Manager& operator= (const Manager& m);
};
Related
We are in the process of deprecating ACE libraries in our project which consists of around 120 binaries and in many of binaries we have used ACE_Singleton.Since after deprecating we will not have this class so we are thinking of writing our own generic singleton in our shared library that is common across all these binaries and one of the goals that we want to achieve is if somebody inherit from this class (using CRTP) say Logger and even when Logger constructor is public then also we cannot create two logger object.
To illustrate let's assume my singleton class name is GenericSingleton and my client class is logger then following code should throw error :
class Logger:public GenericSingleton<Logger>
{
public:
Logger()
{
}
};
int main()
{
Logger obj;// first instance no issue
Logger obj1; // second instance is problem as it is inherited from singleton
}
So can somebody suggest me how GenericSingleton should be designed so that while creating second object i should get compiletime error ?
In short is there a way that if my derived class doesn't have private constructor,destructor copy constructor etc. then it can be checked at compiletime using static_assert ?
There's no way for a constructor to know at compile time where or how many times it will be called; constructors are just functions, and functions don't know anything about their contexts. Consider that any static_asserts will be evaluated when the class is compiled, but this can (and almost certainly will!) happen in an entirely different translation unit from code that actually instantiates the class.
In any case, it seems unlikely that this would be helpful, because you must have some way to access singletons throughout your codebase.
Additionally, it's unclear why you want to permit your singletons to have public constructors. If you want to enforce singleton behavior at compile time for a completely arbitrary class just by adding an inheritance declaration, you're out of luck; arbitrary classes can be, well, arbitrarily constructed.
Since you're transitioning from the ACE singleton, I suggest you use a similar API; note that the ACE singleton documentation recommends making your singleton constructors private.
If, however, you just want some way to force your client to write a constructor that can't (easily) be called improperly, you can do something like this:
template <typename T>
class SingletonBase {
protected: class P { friend class SingletonBase<T>; P() = default; };
public:
SingletonBase(P) {}
static T& Instance() {
static T instance { P {} };
return instance;
}
};
(You will also need to delete the base class's copy and move constructors. Here is a working example use case. Note that declaring P's constructor =default does not prevent the singleton class from default-initializing instances of P. )
Now, because the base class constructor takes an argument of type P, the singleton class implementation must pass a P to its parent class constructor. But since the constructor for P is private, the singleton class won't be able to construct an instance of P except by copy or move construction, so its constructor must take an instance of P. But since P itself is protected, only the singleton class and the parent class can actually use it, so effectively the only possible call to the child's constructor must be in the Instance method.
Note that you do not need to explicitly declare and define the singleton-class's constructor, which would be ugly because of the need to use SingletonBase<Singleton>::P. You can simply expose the constructor with a using declaration:
using BASE = SingletonBase<Myclass>;
using BASE::SingletonBase;
You need to make sure that instances of Logger cannot be created outside the function that creates the sole instance of Logger.
Here's a simple implementation.
template <typename T> class GenericSingleton {
public:
static T& instance() {
static T instance_;
return instance_;
}
};
class Logger: public GenericSingleton<Logger>
{
// Make sure that the base class can create the sole instance of
// this class.
friend GenericSingleton<Logger>;
private:
// Makes sure that you cannot create objects of the class
// outside GenericSingleton<Logger>
~Logger() {}
public:
void foo() {}
};
int main()
{
// OK. Call foo() on the only instance of the class.
Logger::instance().foo();
// Not OK.
Logger obj1;
}
My advice would be to separate concerns. There is the concept of a service (such as a logger) and the service may or may not be a singleton. But this is an implementation detail, and therefore a separate concern. The consumer of the service ought to be agnostic of it.
Now, later in the lifecycle of the project, when you realise that singletons were a terrible idea, you can refactor the singleton without having to refactor any code that depends on it.
e.g.:
template<class Impl>
struct implements_singleton
{
using impl_type = Impl;
static impl_type& get_impl()
{
static impl_type _{};
return _;
}
};
struct logger_impl
{
void log_line(std::string const& s)
{
std::clog << s << std::endl;
}
};
struct logger
: private implements_singleton<logger_impl>
{
void log_line(std::string const& s) {
get_impl().log_line(s);
}
};
void do_something(logger& l)
{
l.log_line("c");
}
int main()
{
logger a;
logger b;
a.log_line("a");
b.log_line("b"); // behind the scenes this is the same logger
// but the user need not care
do_something(a);
}
C++11 introduced the keyword final to forbid future overrides or to prohibit inheritance. The most common example where one may use it is for the case of classes that are not intended to be used as base classes (have e.g. non-virtual destructors). However, sometime we may want to have an is-implemented-in-terms-of relation between two classes (i.e. private inheritance), and not a is-a relationship (public inheritance). However, final prohibits both types of inheritance.
My question is the following: is there any way of allowing private inheritance but forbidding public inheritance (probably not directly, but at least can we "simulate" it)? In this case, there won't be any issues even if we use a class with a non-virtual destructor, as we cannot use directly the derived class via a pointer to base, so we should be fine.
I am thinking of a code like this:
class Base /*final*/ {}; // making it final prohibits both private and public inheritance
class PrivateDerived: private Base{}; // this should work
class PublicDerived: public Base{}; // this shouldn't
int main()
{
PrivateDerived prvd;
PublicDerived pubd; // this should not compile
// Base* pBase = new PrivateDerived; // doesn't work, so we are ok
}
Interesting question! If you don't mind giving up the destructor's triviality, I think the following does the job:
#include <type_traits>
template <typename T>
class Base {
protected:
~Base() {
static_assert(!std::is_convertible<T*,Base*>::value, "Invalid use of public inheritance.");
}
};
class Derived : public Base<Derived> {
};
int main() {
Derived d;
}
The code above fails to compile: the static_assert fires because Derived* is convertible to Base<Derived>*. However if you change the inheritance to either protected or private then the code compiles.
Unfortunately users can still shoot themselves in the foot:
class Bad : public Base<Derived> {
};
I am not sure if this is what you are looking for or if this will help you in your case. I will however demonstrate polymorphic behavior.
Protected Constructor Abstract Class
class BaseProtected {
// ----- Member Variable Section -----
public:
// There Shouldn't Be Public Variables In A Base Class Unless
// That Is The Behavior You Are Looking For - Keep In Mind
// Every Inherited Class & Outside Class Can Change Them.
protected:
// Member Variables Here To Be Shared With Each Derived Class
private:
// Member Variables Here To Be Used By Base Class Only
// ----- Member Function Section -----
public:
virtual ~BaseProtected(); // Virtual Destructor
void somefunc() const; // Common Function Between All Derived Class
virtual void allDerivedMustImplement() const; = 0 // Purely Virtual
protected:
// Default Constructor - Can Not Declare An Instance Of Base Class
BaseProtected(); // Abstract Class
// Protected Functions Shared Between Classes
// Protected Functions That Are Purely Virtual If Needed
private:
// Private Functions Used By Base Class Only
}; // BaseProtected
Derived Class With Possible Inheritance
class DerivedWithPossibleInheritance : public BaseProtected {
// ----- Member Variable Section -----
public:
// Public Member If Giving Free Access
protected:
// Protected Members If Being Inherited From
private:
// Private Members Unique To This Derived Class
// ----- Member Function Section -----
public:
DerivedWithPossibleInheritance(); // Default Constructor
virtual ~DerivedWithPossibleInheritance(); // Virtual Destructor
void uniqueFunctionForThisClass() const;
void allDerivedMustImplement() const override;
private:
// Private Functions Unique To This Class
}; // DerivedWithPossibleInheritance
Derived Class That Can Not Be Inherited From
class DerivedClassCanNotBeInheritedFrom sealed : public BaseProtected {
// ----- Member Variable Section -----
public:
// Public Members Variables
protected:
// Should Not Have Member Variables Here For This Class Can Not Be Inherited from
private:
// Private Members Variables
// ----- Member Function Section ------
public:
DerivedClassCanNotBeInheritedFrom(); // Default Constructor
virtual ~DerivedClassCanNotBeInheritedFrom(); // Default Virtual Destructor
void anotherUniqueFunctionForThisClass() const;
void allDerivedMustImplement() const override;
protected:
// There Should Not Be Any Functions Here This Can Not Be Inherited From
private:
// Private Member Functions Here
}; // DerivedClassCanNotBeInheritedFrom
What I have demonstrated here is the key word sealed when working with inheritance and polymorphism. If you do not want your class to be derived from then use the sealed keyword.
As for declaring any base class, a stand alone class, or a singleton class that has a private Constructor the use of the friend keyword is needed. There are to many types of implementations to get involved with here to show them, but the concept of preventing a class from being inherited from is the same. Personally I have not used the keyword final, but I have used the keyword sealed and it works very good.
I have not used inheritance of classes other then public: So to answer your questions in terms of protected or private inheritance is not something I am real familiar with. But maybe the use of the keyword sealed might help you.
I need a static method of my Base class to have a default parameter value of type Derived.
Is there a way to implement this without use of overloading? (see here).
class Base;
class Derived;
Derived make_derived(void);
class Base
{
public:
static void problem_here(Base && = make_derived());
};
class Derived : public Base
{
};
Derived make_derived()
{
return Derived();
}
... gives me an error about the usage of the incomplete type Derived. How ever, I cannot place the definition of Derived in front of problem_here because it must be defined after the definition of its base class Base.
Unfortunately, returning a pointer from make_derived is not an option.
Overloading problem_here is the only thing I came up with until now, but as the "real" problem_here method takes 2 (and another one 3) parameters, and it's part of a library, this gives me ...
static void problem_here(Thing const &, Base const &);
static void problem_here(Thing const &, Base &&);
static void problem_here(Thing const &); // Default param "hack"
static void problem_here(Thing &&, Base const &);
static void problem_here(Thing &&, Base &&);
static void problem_here(Thing &&); // Default param "hack"
.. for only the two parameter case.
Is there a way to avoid writing all those function signatures, while still maintaining the same performance (no unneccessary copy/move construction for any parameter constellation) and same behaviour on the caller site?
I should add that there are multiple functions like problem_here and all need access to the protected constructor of Derived (and to those of its many siblings). So the main reason to make these methods static members of Base is to be able to friend class Base; in each of the derived classes instead of friending every function.
Refactoring showed me, that I could move the code accessing the protected constructors of the derived classes into a single factory function. That way, I'm able to move the functions with the default parameters outside Base and let the call the factory. Now I still have to friend every one of those functions, but only a single time (in Base to give them access to the factory). I could circumvent this by placing all functions into a helper class and friending it instead, but that looks like a hack to me.
class Base
{
friend class Helper; // The Hack
friend void no_problem_here(Base &&); // No hack, more writting
protected:
static void factory(Thing && from_which_I_can_construct_the_correct_derived_class);
// return type void to keep it simple, move parameter type because special cases
// handled in "trampoline" functions and a copy of the Thing must be stored either
// way.
};
class Derived : public Base
{
friend class Base;
// protected constructor omited for simplicity.
}
void no_problem_here(Base && = make_derived());
// ...
void no_problem_here(Base && b)
{
// work, and then call Base::factory
}
// or
class Helper
{
protected:
// Constructors ...
public:
static void no_problem_either(Base && = make_derived());
};
You can make declarations multiple times, so the following workaround might help:
class Base;
class Derived;
Derived make_derived(void);
class Base
{
public:
static void problem_here(Base &&);
};
class Derived : public Base {};
void Base::problem_here(Base && = make_derived()) { /* ... */ }
If there's a problem factoring the code like that, you can always insert a little trampoline function:
class Base
{
public:
static void problem_here(Base &&);
private:
static void problem_here_impl(Base &&);
};
inline void Base::problem_here(Base && x = make_derived())
{ problem_here_impl(std::move(x)); }
As we all know, some languages have the notion of interfaces. This is Java:
public interface Testable {
void test();
}
How can I achieve this in C++ (or C++11) in most compact way and with little code noise? I'd appreciate a solution that wouldn't need a separate definition (let the header be sufficient). This is a very simple approach that even I find buggy ;-)
class Testable {
public:
virtual void test() = 0;
protected:
Testable();
Testable(const Testable& that);
Testable& operator= (const Testable& that);
virtual ~Testable();
}
This is only the beginning.. and already longer that I'd want. How to improve it? Perhaps there is a base class somewhere in the std namespace made just for this?
For dynamic (runtime) polymorphism, I would recommend using the Non-Virtual-Interface (NVI) idiom. This pattern keeps the interface non-virtual and public, the destructor virtual and public, and the implementation pure virtual and private
class DynamicInterface
{
public:
// non-virtual interface
void fun() { do_fun(); } // equivalent to "this->do_fun()"
// enable deletion of a Derived* through a Base*
virtual ~DynamicInterface() = default;
private:
// pure virtual implementation
virtual void do_fun() = 0;
};
class DynamicImplementation
:
public DynamicInterface
{
private:
virtual void do_fun() { /* implementation here */ }
};
The nice thing about dynamic polymorphism is that you can -at runtime- pass any derived class where a pointer or reference to the interface base class is expected. The runtime system will automatically downcast the this pointer from its static base type to its dynamic derived type and call the corresponding implementation (typically happens through tables with pointers to virtual functions).
For static (compile-time polymorphism), I would recommend using the Curiously Recurring Template Pattern (CRTP). This is considerably more involved because the automatic down-casting from base to derived of dynamic polymporphism has to be done with static_cast. This static casting can be defined in a helper class that each static interface derives from
template<typename Derived>
class enable_down_cast
{
private:
typedef enable_down_cast Base;
public:
Derived const* self() const
{
// casting "down" the inheritance hierarchy
return static_cast<Derived const*>(this);
}
Derived* self()
{
return static_cast<Derived*>(this);
}
protected:
// disable deletion of Derived* through Base*
// enable deletion of Base* through Derived*
~enable_down_cast() = default; // C++11 only, use ~enable_down_cast() {} in C++98
};
Then you define a static interface like this:
template<typename Impl>
class StaticInterface
:
// enable static polymorphism
public enable_down_cast< Impl >
{
private:
// dependent name now in scope
using enable_down_cast< Impl >::self;
public:
// interface
void fun() { self()->do_fun(); }
protected:
// disable deletion of Derived* through Base*
// enable deletion of Base* through Derived*
~StaticInterface() = default; // C++11 only, use ~IFooInterface() {} in C++98/03
};
and finally you make an implementation that derives from the interface with itself as parameter
class StaticImplementation
:
public StaticInterface< StaticImplementation >
{
private:
// implementation
friend class StaticInterface< StaticImplementation > ;
void do_fun() { /* your implementation here */ }
};
This still allows you to have multiple implementations of the same interface, but you need to know at compile-time which implementation you are calling.
So when to use which form? Both forms will let you re-use a common interface and inject pre/post condition testing inside the interface class. The advantage of dynamic polymorphism is that you have runtime flexibility, but you pay for that in virtual function calls (typically a call through a function pointer, with little opportunity for inlining). Static polymporhism is the mirror of that: no virtual function call overhead, but the disadvantage is that you need more boilerplate code and you need to know what you are calling at compile-time. Basically an efficiency/flexiblity tradeoff.
NOTE: for compile-time polymporhism, you can also use template parameters. The difference between static interface through the CRTP idiom and ordinary template parameters is that CRTP-type interface are explicit (based on member functions), and template interface are implicit (based on valid expressions)
What about:
class Testable
{
public:
virtual ~Testable() { }
virtual void test() = 0;
}
In C++ this makes no implications about copyability of child classes. All this says is that the child must implement test (which is exactly what you want for an interface). You can't instantiate this class so you don't have to worry about any implicit constructors as they can't ever be called directly as the parent interface type.
If you wish to enforce that child classes implement a destructor you can make that pure as well (but you still have to implement it in the interface).
Also note that if you don't need polymorphic destruction you can choose to make your destructor protected non-virtual instead.
According to Scott Meyers (Effective Modern C++): When declaring interface (or polymorphic base class) you need virtual destructor, for proper results of operations like delete or typeid on a derived class object accessed through a base class pointer or reference.
virtual ~Testable() = default;
However, a user-declared destructor suppresses generation of the
move operations, so to support move operations you need to add:
Testable(Testable&&) = default;
Testable& operator=(Testable&&) = default;
Declaring the move operations disables copy operations and you need also:
Testable(const Testable&) = default;
Testable& operator=(const Testable&) = default;
And the final result is:
class Testable
{
public:
virtual ~Testable() = default; // make dtor virtual
Testable(Testable&&) = default; // support moving
Testable& operator=(Testable&&) = default;
Testable(const Testable&) = default; // support copying
Testable& operator=(const Testable&) = default;
virtual void test() = 0;
};
Another interesting article here: The Rule of Zero in C++
By replacing the word class with struct, all of the methods will be public by default and you can save a line.
There's no need to make the constructor protected, since you can't instantiate a class with pure virtual methods anyway. This goes for the copy constructor as well. The compiler-generated default constructor will be empty since you don't have any data members, and is completely sufficient for your derived classes.
You're right to be concerned about the = operator since the compiler-generated one will certainly do the wrong thing. In practice nobody ever worries about it because copying one interface object to another never makes sense; it's not a mistake that happens commonly.
Destructors for an inheritable class should always be either public and virtual, or protected and non-virtual. I prefer public and virtual in this case.
The final result is only one line longer than the Java equivalent:
struct Testable {
virtual void test() = 0;
virtual ~Testable();
};
Keep in mind that the "rule of three" is unnecessary if you aren't managing pointers, handles, and/or all the data-members of the class have their own destructors that will manage any clean-up. Also in the case of a virtual base class, because the base class can never be directly instantiated, it's not necessary to declare a constructor if all you're wanting to-do is define an interface that has no data members ... the compiler defaults are just fine. The only item you would need to keep is the virtual destructor if you are planning on calling delete on a pointer of the interface type. So in reality your interface can be as simple as:
class Testable
{
public:
virtual void test() = 0;
virtual ~Testable();
}
I realize how many times this have been talked about but I have not found an appropriate solution for my problem. I have just implemented a Meyer's singleton class into my project but I would like to make a template out of it so that I can use it as e.g.
class Game : public Singleton<Game>
{ /* stuff */
}
And I have my class defined like this
template <typename T>
class Singleton
{
public:
static T& Instance();
private:
Singleton();
//declare them to prevent copies
Singleton(Singleton const&);
void operator=(Singleton const&);
};// END OF CLASS DEFINITION
// METHODS' DEFINITIONS
template<typename T>
T& Singleton<T>::Instance()
{
static T _instance;
return _instance;
}
Allowing ctor to be public will destroy whole vision of Singletons.
EDIT
Ok, so I have updated my Game class to befriend Singleton<Game>
class Game : public Singleton<Game>
{
friend class Singleton<Game>;
//...
}
But now I have something like:
undefined reference to 'Singleton< Game >::Singleton()'
in function Game::Game() which is empty
Allowing ctor to be public will destroy whole vision of Singletons.
No, not really. Game should have a private constructor. Constructor of Singleton is irrelevant. An instance of Singleton<Game> will not help anyone to get another instance of Game, which is what you're interested in.
Anyway, you can declare the constructor protected. Alternatively, you can keep the constructor private and befriend the template parameter. Except this does not work in C++03. Should work in C++11 though. But there's a little trick:
template <typename T>
struct wrapper
{
typedef T type;
};
template <typename T>
class Singleton
{
friend class wrapper<T>::type;
Update: Game should befriend Singleton<Game>, or at least Singleton<Game>::Instance, to allow its constructor to be called.
ctor Singleton() -> protected?