• 4073阅读
  • 2回复

C++ basics: destructor should always be virtual. [复制链接]

上一主题 下一主题
离线steinlee
 

只看楼主 正序阅读 楼主  发表于: 2010-02-18
— 本帖被 午小夜 执行加亮操作(2010-02-20) —
The reason:

class A
{
public:
     A(){}
    virtual ~A() {}
}

class B: public A
{
public:
   B(){}
   virtual ~B(){}
}

A * a = new B;
delete a; a = 0;

If the destructor of A is not virtual, delete a will not incur the destructor of B.
This means that some heap memory in B may be lost.
Looking for remote C/C++ and Qt 兼职
离线午小夜

只看该作者 2楼 发表于: 2010-02-20
  1. /*******************main.cpp*******************/
  2. #include <QtGui/QApplication>
  3. #include "widget.h"
  4. int main(int argc, char *argv[])
  5. {
  6.     QApplication a(argc, argv);
  7.     QWidget* w = new Widget;
  8.     w->show();
  9.     delete w;
  10.     w = NULL;
  11.     return a.exec();
  12. }


  1. /******************widget.h********************/
  2. #ifndef WIDGET_H
  3. #define WIDGET_H
  4. #include <QtGui>
  5. #include <QtCore>
  6. class Widget : public QWidget
  7. {
  8.     Q_OBJECT
  9. public:
  10.     Widget(QWidget *parent = 0){}
  11.     ~Widget(){qDebug()<<"test";}
  12. };
  13. #endif // WIDGET_H


Application Output:   test

so,how come? you know, the destructor  of QWidget is not virtual.
[操作系统版本]  Windows XP;Linux Ubuntu;Linux Fedora;
[Qt SDK版本]    4.7.0
[SDK 发布日期]  2010.05
[IDE(集成开发环境)] QtCreator
个人网页:http://hi.baidu.com/午小夜
學歷:Royal Jalidon
离线henrya2
只看该作者 1楼 发表于: 2010-02-20
很多书上推荐是析构使用虚函数。。。。。
快速回复
限100 字节
 
上一个 下一个