top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

What are virtual destructors and Why they are used?

+2 votes
44 views
What are virtual destructors and Why they are used?
posted Mar 26, 2014 by Maninder Bath

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

2 Answers

0 votes

virtual destructors are same as virtual functions. When an object of subclass is removed, which is referenced by a parent class pointer, only base class destructor will get executed. But if the destructor is defined using virtual keyword, both the destructors will get invoked.

answer Mar 27, 2014 by Pavan P Naik
0 votes

If the destructor in the base class is not made virtual, then an object that might have been declared of type base class and instance of child class would simply call the base class destructor without calling the derived class destructor.
Hence, by making the destructor in the base class virtual, we ensure that the derived class destructor gets called before the base class destructor.

class a
{
           public:          
           a(){printf("\nBase Constructor\n");}
           ~a(){printf("\nBase Destructor\n");} 
};
class b : public a 
{
         public:
         b(){printf("\nDerived Constructor\n");}
         ~b(){printf("\nDerived Destructor\n");} 
};
int main()
{
         a* obj=new b;
         delete obj;
         return 0;
}

Output:
Base Constructor
Derived Constructor
Base Destructor
By Changing 
~a(){printf("\nBase Destructor\n");}
to 
virtual ~a(){printf("\nBase Destructor\n");}
Output:
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
answer Nov 20, 2014 by Manikandan J
Similar Questions
+2 votes

I'm curious as to why libstdc++ is using a RB-tree to implement std::set (details here
https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/std/set and here https://github.com/gcc-mirror/gcc/blob/master/libstdc++-v3/include/bits/stl_tree.h ),
when there are faster alternatives?

I'm mainly curious, because from all the people I've asked there hasn't been a single answer in favor of RB-trees, other than "they're already popular" or "easy to implement".

If you'd like more details on that, here's a link to my question on stackexchange http://cs.stackexchange.com/questions/41969/why-are-red-black-trees-so-popular,
where nobody has yet answered as well.

Using a variant of B-tree (or (a,b)-tree) should be faster, and everyone seems to suggest so, which makes me wonder what is the reason for picking RB-trees? This is not a question about their theoretical speed, but about real world behavior on real hardware with respect to CPU caches, etc.

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...