+ Reply to Thread
Results 1 to 2 of 2

Thread: What is virtual destructor?

  1. #1

    What is virtual destructor?

    Hi All,

    What is virtual destructor? How it is useful?

    Regards.

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    Hi,

    virtual keyword is used to override a method in derived class.

    Overriding a method is using the same function signature in base and derived class and declared method with 'virtual' keyword in base class.

    When there is inheritance user will need to take care of making base class's destructor 'virtual' or else derived class can leak memory as described in below example.

    Code:
    class CBase
    {
    private:
    	char *pBase ;
    public:
    	CBase()
    	{
    		 pBase = new char[100] ;
    		 strcpy(pBase, "CBase::CBase") ;
    	}
    
            //PART 2
    	//virtual ~CBase()
    
            //PART 1
            ~CBase()
    	{
    		if (NULL != pBase)
    		{
    			delete []pBase ;
    			pBase = NULL ;
    		}
    	}
    } ;
    
    class CDerived : public CBase
    {
    	char *pDerived ;
    public:
    	CDerived()
    	{
    		pDerived = new char[100] ;
    		strcpy(pDerived, "CBase::CBase") ;
    	}
    
    	~CDerived()
    	{
    		if (NULL != pDerived)
    		{
    			delete []pDerived ;
    			pDerived = NULL ;
    		}
    	}
    } ;
    
    void UsingVirtualDestructor()
    {
    	CBase *pBase = new CDerived() ;
    
            //if ~CBase() is declare without 'virtual key word as Part 1 then below code will leak memory of CDerived::pDerived member.
            //now comment PART 1 and un-comment PART 2. Memory won't leak. This is magic of virtual keyword!
    	delete pBase ;
    	pBase = NULL ;
    }
    Regards.

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts