I guess Thomas explanation was good enough.. Just a point to add, calling a virtual function with in the destructor is not a good way of doing things. If you have end up with a situation like that, then probably there is a design flaw in your system and you need to consider refining your existing design.
regards, Thangaraj On Sun, Aug 30, 2009 at 8:13 PM, Thomas Hruska <[email protected]>wrote: > > > Sudipta Deb wrote: > > Hi, > > > > I have a doubt. I know that the destructor can call virtual member > function. But can somebody please tell me is there any problem if destructor > do the same? > > > > With regards, > > Sudipta > > Seems pretty iffy. Assuming all your destructors are virtual when you > use base and derived classes (which they should be), the destructors are > called from most derived to base. If you call a virtual member function > and the data that the function tries to access has gone away (been > deleted), then you will probably introduce a crash bug or memory leak. > > class Base > { > public: > Base() > { > } > > virtual ~Base() > { > SomeFunc(); > } > > virtual void SomeFunc() > { > } > }; > > class Derived : public Base > { > public: > Derived() > { > } > > virtual ~Derived() > { > } > > virtual void SomeFunc() > { > x = "Hi"; > } > > private: > string x; > }; > > Derived goes away first, then Base calls the virtual function but 'x's > memory has already been freed. It may still work depending on how > 'string' operates behind the scenes - that is, it may allocate memory > and work anyway but its destructor won't be called again, leaving you > with a memory leak. > > -- > Thomas Hruska > CubicleSoft President > Ph: 517-803-4197 > > *NEW* MyTaskFocus 1.1 > Get on task. Stay on task. > > http://www.CubicleSoft.com/MyTaskFocus/ > > > [Non-text portions of this message have been removed]
