Example:
class Base {
public:
virtual void f() = 0;
virtual ~Base() { std::cout << "Base::~Base()\n"; }
};
class Derived : public Base {
public:
void f() { }
~Derived() { std::cout << "Derived::~Derived()\n"; }
};
int main() {
Base* p = new Derived();
delete p;
return 0;
}
Output:
Derived::~Derived()
Base::~Base()
I thought only the derived class destructor will be called since the pointed object to be freed is an instance of the derived class.
I have two questions:
- Why was the virtual base destructor called?
- Is it legally possible (or should it even be possible) to prevent the base class destructor from being called?
Because base class should be properly destructed. Derived class can not possibly do this.
No, because it would prevent properly destructing the base class (i.e. call it's members destructors)