Re: Problem with virtual destructor
ZikO wrote:
What's wrong with this code?
You've instantiated a class that has no destructor.
Why can't I compile this?
You can. You just can't link it.
I have created a virtual destructor in one of my code in a base class to
be sure objects of all derived classes would be destroyed.
You declared a pure virtual destructor, but did not define it.
However, the
compiler says "no" with this comments:
C:\DOCUME~1\User\LOCALS~1\Temp/ccLAUiQR.o:test2.cpp:(.text$_ZN1BD2Ev[B::~B()]+0x17):
undefined reference to `A::~A()'
C:\DOCUME~1\User\LOCALS~1\Temp/ccLAUiQR.o:test2.cpp:(.text$_ZN1BD0Ev[B::~B()]+0x17):
undefined reference to `A::~A()'
C:\DOCUME~1\User\LOCALS~1\Temp/ccLAUiQR.o:test2.cpp:(.text$_ZN1BD1Ev[B::~B()]+0x17):
undefined reference to `A::~A()'
collect2: ld returned 1 exit status
Those errors are from ld, the linker.
This is a simple code which roughly represents the problem:
// code
#include <iostream>
using namespace std;
class A {
public:
virtual ~A() = 0;
~A is pure virtual, so A can only be instantiated as a base object of
other class instances. If you just want it to be virtual, define it:
virtual ~A() { }
Even if you really want ~A to be pure virtual, you can still define it
after the class definition:
};
A::~A() { }
class B : public A {};
class C : public B {};
class D : public C {};
int main(int argc, char *argv[])
{
D d;
D has a sub-object of type A. The run-time environment will call ~A,
but since ~A is undefined. The linker will report this.
A &a = d;
return 0;
}
// end of code
Without lines in main everything compiles successfully.