virtual destructor

how virtual destructor is possible

Comments

  • : how virtual destructor is possible
    :
    [blue]Can you rephrase your question?
    It is like asking: "How classes are possible in C++?"
    Compiler knows that some destructors are virtual and generates the correct code for your program.[/blue]
  • : : how virtual destructor is possible
    : :
    : [blue]Can you rephrase your question?
    : It is like asking: "How classes are possible in C++?"
    : Compiler knows that some destructors are virtual and generates the correct code for your program.[/blue]

    well i just wanna ask that can we make a destructur virtual...actually
    i hv read sm rules related to virtual function n it was written thr that
    constructor can not be virtual or destructur can be virtual.....how cm

    :

  • Why do you think a destructor can NOT be virtual? It is just a special-named function which is called automatically at destruction.

    This important for cleaning up: suppose a class called 'Base', having two different derived classes 'Derived1' and 'Derived2' and both derived classes have different resources to deallocate, then it is a good thing the destructor is virtual.

    [code]
    //Empty abstract base class
    struct Base
    {
    virtual ~Base() = 0;
    };

    struct Derived1 : public Base
    {
    SomeResource1 mSomeResource1;
    ~Derived1() { mSomeResource1.free(); }
    };

    struct Derived2 : public Base
    {
    SomeResource2 mSomeResource2;
    ~Derived2() { mSomeResource2.deallocate(); }
    };
    [/code]

    If you don't see why, imagine the destructor NOT being virtual. Then you would needed to call a method called 'Cleanup' or 'Destruct' before destruction. This method would then be virtual!

    [code]
    //Empty abstract base class
    struct Base
    {
    virtual void destruct() = 0;
    };

    struct Derived1 : public Base
    {
    SomeResource1 mSomeResource1;
    void destruct() { mSomeResource1.free(); }
    };

    struct Derived2 : public Base
    {
    SomeResource2 mSomeResource2;
    void destruct() { mSomeResource2.deallocate(); }
    };
    [/code]

    See ya,
    bilderbikkel

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories