Destructor Question? - Programmers Heaven

Howdy, Stranger!

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

Categories

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.