Juha Nieminen wrote:
Noah Roberts wrote:
>There are numerous reasons why you would not want to allow direct
instantiation of a class or base.
Can you give an example of such situation, where it cannot be done by
putting a pure virtual function in the base class?
struct Base
{
private:
struct impl;
impl * pimpl;
protected:
Base();
public:
boost::shared_ptr<Baseconstruct_base();
/* ... functionality - virtuals but no pure */
};
struct Derived
{
private:
struct impl; impl * pimpl;
Derived();
public:
boost::shared_ptr<Derivedconstruct_derived();
/* behavior overrides */
};
Derived.cpp:
Derived::Derived() : Base(), pimpl(new impl) {}
You might consider this idiom any time you want to be sure an object is
never constructed on the stack and never NOT put in a shared_ptr (such
as when also subclassing shared_ptr_from_this).
Another example would be the use of a factory. You want to be sure the
object is always created through the factory but it also needs to be
constructed. The abstraction a factory generates is usually a real
abstract object, but maybe that's not appropriate in all cases. You can
toss in a pure virtual for no reason other than to not have to protect
your constructor, but what's the point in that?? Furthermore you'd
still want to protect construction of derived objects and might wish to
allow them also to be extended by subclassing.
Finally, protecting the constructor says something about the object. It
says that constructing this object through the constructor is not in its
public interface.
Those are the cases I can think of on the spot.