+ Reply to Thread
Results 1 to 2 of 2

Thread: Can default destructor be virtual in C++?

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Posts
    20

    Can default destructor be virtual in C++?

    Following code has base class with virtual method:

    Code:
    class CBase
    {
    public:
    	virtual int GetData()
    	{
    		return 10 ;
    	}
    } ;
    
    class CDerive : public CBase
    {
    public:
    	virtual int GetData()
    	{
    		return 42 ;
    	}
    } ;
    Can default destructor be virtual in C++?

    Or Do I need to override the constructor in class to make it virtual?

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    No, default destructor is not a virtual one.

    Following example does not call destructor of derive class!

    Code:
    class CBase
    {
    public:
    	virtual int GetData()
    	{
    		return 10 ;
    	}
    } ;
    
    class CDerive : public CBase
    {
    public:
    	virtual int GetData()
    	{
    		return 42 ;
    	}
            ~CDerive()
    	{
    	}
    } ;
    void UseInheritance()
    {
    	CBase *pBase = new CDerive() ;
    	int nData = pBase->GetData() ;
    	delete pBase ;
    	pBase = NULL ;
    }
    So, you will need to write your own version of destructor with virtual keyword.

    Hope this helps.

+ Reply to Thread

Tags for this 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