Next: Subclassing library_base, Previous: Supporting auto-detection, Up: Implementing new library classes
In cases where it is inappropriate to use the auto-detection mechanism an
alternative way of initialising library with a pointer to a subclass of
library_base must be provided. To do this, the implementation should
provide subclasses of both library and library_base. The
constructor of the subclass of library should call down to
protected library::library (library_base* lb) constrctor with
a newly allocated subclass of library_base. For example,
class mylibrary : public library {
private:
class impl : public library_base {
// override virtual functions
};
impl *init_library() {
// Do any necessary initialisation
return new impl;
}
public:
mylibrary() : library( init_library() ) {}
};
Usually it is sensible to avoid putting any data members or virtual
functions in mylibrary, and to put them into mylibrary::impl
instead. This means that if a mylibrary class is sliced to a
library during a copy (for example when passing to a function taking
a library by value) the class will still work correctly.
Note that library::~library is not virtual, and thus,
if mylibrary is ever allocated on the heap, care is required to avoid
deletion via a pointer to its base class.