Restricting instantiation of the object in heap only for the particular case

Discussion in 'C++' started by WittyGuy, Aug 29, 2007.

  1. WittyGuy

    WittyGuy Guest

    Hi
    My class looks something like this:

    class Base
    {
    public:
    Base () {}
    ~Base () {} // No virtual dtor in the base class
    private:
    };

    class Derived :
    public Base
    {
    public:
    Derived () {}
    ~Derived () {}
    private:
    };

    int
    main ()
    {
    Base *pB = new Derived; // how to *restrict* this type of
    instantiation
    delete pB;

    Derived *pD = new Derived; // Should allow this type of
    instantiation
    delete pD;

    return 0;
    }

    As given in the above sample code, how to restrict the instantiation
    of derived class object in the heap when it's assigned to a Base class
    pointer rather should allow the same if it's assigned to pointer of
    same type. Coz the later form of instantiation can be allowed as there
    is no harm of memleak though virtual dtor is not defined in base
    class.

    Basically this query araised coz, I'm inheriting from stl container.
    Yes I know ideally I shouldn't have done this coz STL container's dtor
    are not virtual dtor. But anyways if there is a way of restricting the
    instantiation of object as explained above, it should solve my
    problem.

    -Wg-
     
    WittyGuy, Aug 29, 2007
    #1
    1. Advertisements

  2. Undefined behaviour.
    Huh?... If your base class is not declared 'protected' or 'private',
    the conversion from any pointer to derived to a pointer to base is
    valid. There is no way for the compiler to know where the pointer
    comes from to restrict such conversion. You, and only you, can do
    that by declaring protected or private inheritance:

    class Derived : protected Base {};
    If all you want is to prohibit implicit derived-to-base conversion,
    make your base class protected or private.
    In most cases it would be recommended to derive privately and then
    reimplement all the necessary functionality in terms of the base
    class.
    No. Public inheritance *means* conversion of pointer (or reference)
    to derived to pointer (reference) to base is allowed.

    V
     
    Victor Bazarov, Aug 29, 2007
    #2
    1. Advertisements

  3. you cant prevent form Base* bp =new Derived , but you can prevent
    deleting Derived through bp pointer by declaring Base's destructor
    protected. But again since the base class is STL container there isn't
    much you can do.
     
    hurcan solter, Aug 29, 2007
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.