Destructor not called in inheritance

This is a discussion on Destructor not called in inheritance within the C++ Programming forums, part of the General Programming Boards category; I'm totally stalled, after battling this bug for hours after hours my worst fears came true. In the sample code ...

  1. #1
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145

    Destructor not called in inheritance

    I'm totally stalled, after battling this bug for hours after hours my worst fears came true. In the sample code below, where B inherits from A but is still pointed at by an A* pointer the B destructor IS NOT called (even if they use virtual methods). Now a solution/workaround to this is not hard to make, but is this really intended (standard) behavour or is my compiler just plain insane? I can't believe I've never discovered this earlier...
    Code:
    #include <iostream>
    
    class A
    {
    	public:
    		A() { std::cout << "A::A()" << std::endl; }
    		~A() { std::cout << "A::~A()" << std::endl; }
    
    	protected:
    };
    
    class B : public A
    {
    	public:
    		B() { std::cout << "B::B()" << std::endl; }
    		~B() { std::cout << "B::~B()" << std::endl; }
    
    	protected:
    };
    
    int main()
    {
    	A* b = new B();
    	delete b;
    
    	return 0;
    }
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    You must make the destructor of the base class virtual. Then all will be well.

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    thanks
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Destructor being called on SGI hash_map key
    By cunnus88 in forum C++ Programming
    Replies: 4
    Last Post: 02-11-2009, 12:05 AM
  2. Functions which return a reference
    By Stonehambey in forum C++ Programming
    Replies: 10
    Last Post: 07-05-2008, 02:43 PM
  3. Construstors: Called When and How in Other Objects?
    By HalNineThousand in forum C++ Programming
    Replies: 5
    Last Post: 03-27-2008, 07:46 PM
  4. inheritance and performance
    By kuhnmi in forum C++ Programming
    Replies: 5
    Last Post: 08-04-2004, 01:46 PM
  5. Inheritance and virtual functions
    By Cryptomega in forum C++ Programming
    Replies: 5
    Last Post: 02-28-2003, 02:59 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21