c++destructorvirtual-destructor

Virtual destructor, what would happen I didnt have a destructor in the derived class?


I've just had my lesson about virtual destructors and I have a question.

Lets say we have this code below:

#include <iostream>

class Base {
public:
    virtual void fun() { std::cout << "Base Fun" << std::endl; };
    virtual ~Base() { std::cout << "Base Destructor called" << std::endl; };
};

class Derived : public Base {
public:
    virtual void fun() { std::cout << "Derived Fun" << std::endl; };
    ~Derived() { std::cout << "Derived Destructor called" << std::endl; };
};

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

    b->fun();
    d->fun();

    delete b;
    delete d;

    return 0;
}

We see that we have a Virtual destructor in our Base clase, which means when we delete d in our main, both the Base class destructor will be called and the Derived class destructor will be called..

**But what if we didnt have a destructor in our derived class, and we still wanted had the virtual destructor + we still wanted to delete d. What happens then? Does the derived class automatically "create" a destructor, and would the destructor then handle the ressource - d and delete it?


Solution

  • All classes have a destructor. If you don't write one explicitly, then compiler will implicitly generate it. Thus the case you are asking about "if I didn't have a destructor" doesn't exist.

    and would the whole program still work as earlier?

    It would work but not quite the same way since the implicitly generated destructor wouldn't print the string that your destructor prints.