Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 752
KBabuin Avatar asked Feb 18 '26 17:02

KBabuin


2 Answers

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.

like image 153
NathanOliver Avatar answered Feb 21 '26 07:02

NathanOliver


It is supposed that the class can be inherited. Otherwise it should be declared with specifier final.

Take into account that data members of the class have access control specifier protected. It means that the author of the class does not exclude that the class can be inherited.

like image 40
Vlad from Moscow Avatar answered Feb 21 '26 06:02

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!