Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Destructor Question?

ferdinandngferdinandng Posts: 62Member
Hi Experts,

I am new to C++. I want to ask is that if my class inherited from a parent class, when implemnting the my class's destructor, how do I call the parent's destructor? or the compiler will call the parent destuctor method automatically.

Thank you for your help.

Best Regards
Ferdinand Ng

Comments

  • DonotaloDonotalo Posts: 715Member
    : Hi Experts,
    :
    : I am new to C++. I want to ask is that if my class inherited from a parent class, when implemnting the my class's destructor, how do I call the parent's destructor? or the compiler will call the parent destuctor method automatically.
    :
    : Thank you for your help.
    :
    : Best Regards
    : Ferdinand Ng
    :
    [purple]when a derived class' destructor is called, generally the base's destructor will be called automatically. but if u use dynamic allocation of a derived object to a pointer of the base class, then define the base class' destructor as [blue]virtual[/blue], otherwise, the derived class' destructor will not be called when u deallocate memory. here is a short example:[code]
    class Base {
    public:
    Base() {cout << "Base constructed.
    ";}
    virtual ~Base() {cout << "Base destructed.
    ";}
    };

    class Derived : public Base {
    public:
    Derived() {cout << "Derived constructed.
    ";}
    ~Derived() {cout << "Derived destructed.
    ";}
    };

    int main()
    {
    Base *b;
    b = new Derived;
    delete b;

    return 0;
    }
    [/code]
    in the code above, if [blue]~Base()[/blue] would not be defined virtual, [blue]~Derived()[/blue] would not be called.
    [/purple]
    [hr][purple]~Donotalo()[/purple]

Sign In or Register to comment.