OOP Basic–Constructor&Destructor

來源:互聯網
上載者:User

Q:   
     In MFC Libraby, there is no doubt for the importance of  the class CObject. and in the defition of CObject, wen found an interesting thing, that is :the destructor of CObject is virtual. why the coder of MFC think that virtual destructors are necessary?(MOTO 2004)

Explanation:
e.g. we can create a class like this:
class CBase
{
public:
    ~CBase(){.....};
};

class CChild:CBase
{
public:
    ~CChild(){.....};
};
    
main()
{
Child C;
...
return 0;
}

    when the program is running, because that a Child object --C is created, therefore before the constructor of Child is called, the constructor of Base should be called firstly. So, when C  is being killed, it should firstly call the desctructor of Child and then Base (comments: opposite sequence calling constructor and desctructor). that is to say. whatever if destructor is virtual function or not,  when the derived class object is killed, it must call the desctructor of base class orderly.
    Therefore, why does CObject make destructor virtual?
    That 's because Polymorphism.
    take examples continued with the above sample. if there are codes in main function like this:
    CBase *pBase;
    Child c;
    pBase =&c;
    delete pBase;
    then when pBase point is being killed, which destructor is being called, is that of CBase or CChild?
the answer is CBase apparently (static compiling). But if the constructor of CBase is changed into virtual, when pBase is being killed, it will call the destructor of CChild  firstly and then CBase secondly.
       From the above sample, it seems that no errors at all. But if the constructor of Child allocate memory in Heap Area. while its destructor is not virtual. when pBase point is killed, the heap memory that is allocated to CChild Object will not be deallocate . then memory leak occurs!

another Demo for shows:

// virtual.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "string.h"
#include "stdlib.h"
#include "assert.h"
class A
{
public:
    A(char *username)
    {
        int len;
        len=strlen(username);
        m_username=new char[len+1];//(char*)malloc(sizeof(len+1));
        strcpy(m_username,username);
        printf("Username is %s\n",m_username);
    }
/**//*
    virtual ~A()
    {
        delete m_username;
        printf("A is destructed\n");
    }

*/
     ~A()
    {
        delete m_username;
        printf("A is destructed\n");
    }


protected:
    char *m_username;

};

class B:public A
{
public:
    B(char *username,char *password):A(username)
    {
        int len=strlen(password)+1;
        m_password=new char[len];//(char *)malloc(sizeof(len));
        strcpy(m_password,password);
        printf("username:%s,password:%s\n",m_username,m_password);
    }
    ~B()
    {
        delete m_password;
        printf("B is destructed\n");
    }
protected:
    char *m_password;
};

int main(int argc, char* argv[])
{
    B b("herengang","982135");
    A *a=&b;
    delete a;    
    return 0;


}

在這種情況下,我們看到的運行結果如下:

可以看到,B的解構函式根本沒有運行,這樣在B中申請的heap空間 m_password就不會釋放掉,從而造成memory leak!
        而如果我們將A的解構函式改稱virtual之後,其運行結果如下:

        可以看到,所有heap上資源全部釋放

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.