Can a destructor be pure virtual in C++?
标准c++允许纯虚构函数的存在, 但是前提是必须提供定义. 这个就有点矛盾. 纯虚函数还要定义? 原因因为子类的虚函数是按逆序执行的, 最后肯定会调用基类的虚构函数, 如果没有虚构函数的定义, 调用就会产生UD(undefined behavior)
如下代码:
#include <iostream>
class Base
{
public:
virtual ~Base() = 0; // Pure virtual destructor
};
/**
inline Base::~Base() { std::cout << "~Base() is executed\n"; }
*/
class Derived : public Base
{
public:
~Derived()
{
std::cout << "~Derived() is executed\n";
}
};
int main()
{
Base *b = new Derived();
delete b;
return 0;
}
gcc下编译, 链接器会报如下错误:
In function `ZN7DerivedD1Ev':
undefined reference to `Base::~Base()'
将注释部分放开后, 编译通过, 运行后的结果:
~Derived() is executed
~Base() is executed
Warning
一个类如果只包含纯虚构函数, 它就成了纯虚类(即使提供定义), 也就是我们不能创建它. 例子
#include <iostream>
class Base
{
public:
virtual ~Base() = 0; // Pure virtual destructor
};
inline Base::~Base() { std::cout << "~Base() is executed\n"; }
int main()
{
Base *b = new Base();
delete b;
return 0;
}
gcc下编译, 编译报错如下:
error: invalid new-expression of abstract class type 'Base'
note: because the following virtual functions are pure within 'Base':
note: virtual Base::~Base()|
Another peculiar thing
我们知道, 如果子类继承自纯虚类, 那么我们必须为每个纯虚函数提供定义, 但是析构函数例外. 例子如下
#include <iostream>
class Base
{
public:
virtual ~Base() = 0; // Pure virtual destructor
};
inline Base::~Base() { std::cout << "~Base() is executed\n"; }
class Derived : public Base
{
// no definition for destructor
};
int main()
{
Base *b = new Derived();
delete b;
return 0;
}
这段代码在gcc下顺利编译运行. 结果如下:
~Base() is executed