The pure virtual destructor
in base class should have a definition. Otherwise compiler will generate a call to base class destructor from the derived class destructor during link-time and will cause a link-error.
I tried to define the pure virtual destructor inside the base class like below:
class base
{
public:
base()
{
cout << "constructor in base class\n";
}
virtual ~base()=0
{}
};
This gave the compilation error:
error: pure-specifier on function-definition
Then i tried to define the function outside the base class like below:
class base
{
public:
base()
{
cout << "constructor in base class\n";
}
virtual ~base()=0;
};
base::~base()
{
}
This removes the compilation error and it behaves as my understanding.
But my question is how does defining the pure virtual destructor outside the base class removes the compilation error?
Yes, it is possible to have a pure virtual destructor. Pure virtual destructors are legal in standard C++ and one of the most important things to remember is that if a class contains a pure virtual destructor, it must provide a function body for the pure virtual destructor.
It is must to provide a function body for pure virtual destructor as derived class's destructor is called first before the base class destructor, so if we do not provide a function body, it will find out nothing to be called during object destruction and error will occur.
Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior.
While defining (providing an implementation) pure virtual methods is rarely useful, you must define a pure virtual destructor. This is because the destructor of a base class is always called when a derived object is destroyed. Failing to define it will cause a link error.
Your second example is correct.
A lot of the other answers assume that it is illegal to have a pure virtual function with a default implementation, however that is incorrect.
In the case of a pure virtual destructor you must have a definition (see the link in xmoex answer).
It is true that:
§10.4/2 a function declaration cannot provide both a pure-specifier and a definition
However, as you noticed it possible to provide a definition outside of the declaration.
i looked at this page:
http://www.gotw.ca/gotw/031.htm
and from my understanding a pure virtual destructor must have a definition (even an empty one) as every derived class has to call the base classes destructor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With