Thread: Destructor Override!

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    99

    Destructor Override!

    referring to - "http://msdn2.microsoft.com/en-us/library/szx2ta7y(vs.80).aspx"

    "There are two restrictions on the use of destructors. The first restriction is that you cannot take the address of a destructor. The second is that derived classes do not inherit their base class's destructors. Instead, as previously explained, they always override the base class's destructors."

    Can some1 show me an example code, which confirms that derived class overrides
    base class's ?

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    This is the best I can come up with. The base class destructor is overridden by the default destructor, which destructs each member and then calls the base class destructor.

    You can also override the base class destructor in derived yourself, which would be obvious. The only strange thing is that the calling of the base class destructor at the end of the derived class destructor is automatic.
    Code:
    #include <iostream>
    
    class base
    {
    public:
      virtual ~base() { std::cout << "In base destructor.\n"; }
    };
    
    class member
    {
    public:
      ~member() { std::cout << "In member destructor.\n"; }
    };
    
    class derived : public base
    {
      member m;
    };
    
    int main()
    {
      {
        derived d;
      }
    }

Popular pages Recent additions subscribe to a feed