Search code examples
c++inheritancevirtual-destructor

Why virtual destructor?


I am going through some code,plan to adapt it for my research.So header file looks like this

#ifndef SPECTRALCLUSTERING_H_
#define SPECTRALCLUSTERING_H_

#include <vector>
#include <eigen3/Eigen/Core>

class SpectralClustering {
public:
    SpectralClustering(Eigen::MatrixXd& data, int numDims);
    virtual ~SpectralClustering();

    std::vector<std::vector<int> > clusterRotate();
    std::vector<std::vector<int> > clusterKmeans(int numClusters);
    int getNumClusters();

protected:
    int mNumDims;
    Eigen::MatrixXd mEigenVectors;
    int mNumClusters;
};

#endif /* SPECTRALCLUSTERING_H_ */

Latter in the main code

#include "SpectralClustering.h"
#include <eigen3/Eigen/QR>

SpectralClustering::SpectralClustering(Eigen::MatrixXd& data, int numDims):
    mNumDims(numDims),
    mNumClusters(0)

So I do not understand why virtual destructor was used in the .h file. From this we can learn that virtual destructors are useful when you can delete an instance of a derived class through a pointer to base class.But I think this is not case with this code.Can someone explain all this?


Solution

  • The reason you would make a destructor virtual is that you plan for that class to be inherited and used polymorphicly. If we had

    class Foo {};
    class Bar : public Foo {};
    
    Foo * f = new Bar();
    delete f; // f's destructor is called here
    

    The destructor for Foo would be called and no members of the Bar part of the object would be destroyed. If Foo had a virtual destructor then a vtable lookup would happen the the Bar destructor would be called instead correctly destroying the object.