i have been thinking, why only base class with virtual method needs virtual desctructor? look at this piece of code (read the comment):
class Base{
private:
int x;
public:
Base():x(0){}
~Base(){
cout<<"Base dtor"<<endl;
}
};
class Derived : public Base{
int y;
public:
Derived():y(0){}
~Derived(){
cout<<"Derived dtor"<<endl;
}
};
int main(){
Derived *pd = new Derived;
Base *pb = pd;
delete pb; // this destroys only the base part, doesn't it?
// so why doesnt the derived part leak?
return 0;
}
I ran it with Valgrind and saw that the output was "Base dtor", and no memory leaks occurred. So, if only the base class dtor was called, why doesn't the derived class part leak?