+ Reply to Thread
Results 1 to 2 of 2

Thread: Why my derived class's destructor does not get called?

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    29

    Why my derived class's destructor does not get called?

    Example:

    Code:
    class A
    {
    public:	
    	A()
    	{
    	}
    
    	~A()
    	{
    	}
    } ;
    
    
    class B : public A
    {
    public:	
    	B()
    	{
    	}
    
    	~B()
    	{
    	}
    } ;
    
    void MyInheritance()
    {
          A *pA = new B() ;
    
         delete pA ;
    }
    Above code does not call destructor of my derived class.

    How can I resolve this issue?

    Please help.

  2. #2
    Junior Member
    Join Date
    Feb 2012
    Posts
    48
    You forgot to add virtual keyword in destructor of base class. This is the key.

    Code:
    class A
    {
    public:	
    	A()
    	{
    	}
    
    	virtual ~A() //note here, virtual keyword!
    	{
    	}
    } ;
    
    
    class B : public A
    {
    public:	
    	B()
    	{
    	}
    
    	~B()
    	{
    	}
    } ;

+ 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