: 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
:
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 virtual, otherwise, the derived class' destructor will not be called when u deallocate memory. here is a short example:
class Base {
public:
Base() {cout << "Base constructed.\n";}
virtual ~Base() {cout << "Base destructed.\n";}
};
class Derived : public Base {
public:
Derived() {cout << "Derived constructed.\n";}
~Derived() {cout << "Derived destructed.\n";}
};
int main()
{
Base *b;
b = new Derived;
delete b;
return 0;
}
in the code above, if ~Base() would not be defined virtual, ~Derived() would not be called.
~Donotalo()