0

I have searched many sites and also there are questions on stackoverflow regarding my question but none answers them perfectly,so i decided to frame it as a new question. According to me we use 'virtual' keyword when we need to define the function with same name and argument-list in both base and derived class.But in case of the destructos why we need virtual as the names would be different and there should be no confusion for the compiler as in case o constructor. I am really confused with this.

Omkar
  • 521
  • 1
  • 7
  • 23
  • Possible duplicate of [When to use virtual destructors?](http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors) – paisanco Oct 28 '15 at 03:02
  • @paisanco :I have already gone through your mentioned post and didn't get a perfect answer for my question.That post states what happens with and without virtual destructor which was not the issue i wanted answer for. – Omkar Oct 28 '15 at 03:34

1 Answers1

0

In an object hierarchy, you can store your objects in a collection of your base object. In order to make sure your derived types' destructor is also executed during cleanup, you should make your dtors virtual.

However, you might not always want that, and hence c++ (I suppose yours is a c++ question), or the language gives you the chance to control this behaviour.

mentat
  • 2,668
  • 1
  • 19
  • 39
  • I have got the need for virtual but why only virtual?What is making it work with virtual?Can you please comment for the specific question on the second line of my question. – Omkar Oct 28 '15 at 03:37
  • I don't understand your question, why only virtual? virtual keyword is the means to tell compiler your function can have a replacement in derived types. I suppose you have some mixing function overriding and virtual inheritance. At least in c++, you can override a function without declaring it as virtual. All depends on what you want to achieve.. – mentat Oct 28 '15 at 03:48
  • Sorry for not being able to frame my question in a clear and concise way.Yes i am confused a little in overriding.You said "replacement in derived types" but then as the destructor names would be different ex.~A() and ~B() (where B inherits A) why would we use virtual,as the declaration is different the functions are different. – Omkar Oct 28 '15 at 04:04
  • virtual destructors are really a special case to handle memory leaks and cleanups, try googling. as I said in my original response, in some cases, you might *not* want to have virtual destructors (eg: if you won't cleanup any dynamic allocations and want to be fast). ability to use virtual keyword on destructors gives you the freedom to choose as a developer. – mentat Oct 28 '15 at 04:08