Thread: virtual destructor problem

  1. #1
    Bond sunnypalsingh's Avatar
    Join Date
    Oct 2005
    Posts
    162

    virtual destructor problem

    Code:
    #include <stdio.h>
    
        class Person
    	{ 
    	public: ~Person(){}
    	};
        class Englishman :public Person
        { 
    	public: virtual ~Englishman()
    		{ 
    				printf( "Goodbye\n" ); 
    		}
    	};
        class Japanese : public Person
        { 
    	public: virtual ~Japanese()
    			{
    				printf( "Sayonara\n" ); 
    			} 
    	};
       class German :public Person
       { 
       public: virtual ~German()
    		   {
    			   printf( "Auf Wiedersehen\n" ); 
    		   } 
       };
    
       int main()
           {
           Person *p = new Japanese;
           delete p;
           p = new German;
           delete p;
           return 0;
           }
    Since base class destructor is not declared virtual...that is why destructors of derived are not getting called...but why does the code crash....when i don't add virtual keyword to derive class destructors then my code does not crash

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Not having a virtual destructor in your Person class means that the two "delete p;" lines in main() both yield undefined behaviour, according to the C++ standard. Undefined behaviour means that anything is allowed to happen. A program crash is one of the options within "anything". As is having that crash go away when you change the derived classes.

    The practical reason (if you look into the guts of the compiler and how it does things) probably comes down to the fact that virtual functions are often implemented as pointers to functions which exist in some class (and compiler) specific table (i.e. an internal data structure, often referred to as a virtual function table), and classes without any virtual functions do not have such a table. So, the "undefined behaviour" in this case probably involves some form of invalid pointer operation when attempting to find destructors to call.
    Last edited by grumpy; 10-15-2005 at 05:13 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Virtual Box
    By ssharish2005 in forum Tech Board
    Replies: 3
    Last Post: 02-12-2009, 05:08 AM
  2. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  3. Program with Shapes using Virtual Functions
    By goron350 in forum C++ Programming
    Replies: 12
    Last Post: 07-17-2005, 01:42 PM
  4. C++ XML Class
    By edwardtisdale in forum C++ Programming
    Replies: 0
    Last Post: 12-10-2001, 11:14 PM
  5. Exporting Object Hierarchies from a DLL
    By andy668 in forum C++ Programming
    Replies: 0
    Last Post: 10-20-2001, 01:26 PM