Search code examples
c++classinheritancevirtual-destructor

C++ Error when using virtual destructor


I have implemented an interface:

class ISolution
{
public:
  virtual ~ISolution() = 0;

  virtual void resultat() = 0;
};

and some derived classes from it:

class SolX : ISolution
{
private:
  int member;
  MyClass myOb;
public:
  SolX(const MyClass& inOb) : myOb(inOb) {}
  ~SolX() {}

  void resultat()
  {
    // the body
  }
};

When I compile it I get errors like:

/proj/CSolution1.cpp:4: undefined reference to `ISolution::~ISolution()'
/proj/CSolution2.cpp:4: undefined reference to `ISolution::~ISolution()'
CMakeFiles/proj.dir/CSolution2.cpp.o:/proj/CSolution2.cpp:12: more undefined references to `ISolution::~ISolution()' follow

I am using CMake and Linux Ubuntu.

I cannot figure out what is the problem. Is there something that I have missed? Does myOb create the problems?

P.S.: The line where is the error is at the definition of the constructor.


Solution

  • The problem is

    virtual ~ISolution() = 0;
    

    the destructor is not implemented. Try

    virtual ~ISolution() { }
    

    instead.

    This is needed even when only instances of the derived class are created, because destructors are special. In a normal function, the base class implementation needs to be called explicitly, like

    void Derived::Foo() {
        Base::Foo();
        ....
    }
    

    but for a destructor, this is always done automatically.