Virtual Destructors and Constructors in C++

In C++ you can have virtual destructors but NOT virtual constructors. This is because when an object has virtual functions it must have an associated v-table which keeps track of the addresses to the virtual functions for that class.  That would mean that an object must be instantiated firstly before a v-table for that object could exist.  Since constructors are intended to instantiate and create the object there can be no virtual constructor.

On the other hand a virtual destructor is allowed and should be used when ever there are virtual methods in the base class.  The misuse of virtual destructors can lead to memory leaks and bad side effects.  The following code tries to explain this problem.

void goodbye(const char* clsid) { std::cout << "Good-bye, " << clsid << "!" << std::endl; } class Foo { public: ~Foo() { goodbye("Foo"); } }; class Bar : public Foo { public: ~Bar() { goodbye("Bar"); } }; int main (int argc, char * const argv[]) { Foo* p = new Bar; delete p; return 0; }

In the above code example when the object that p is pointing to is destroyed the output will be “Good-bye, Foo!”.  The destructor for Bar will not be called.  That behavior is most likey not desired.  Making the destructor in Foo virtual will resolve this problem and the output would be:

Good-bye, Bar!
This entry was posted in Development and tagged , . Bookmark the permalink.

4 Responses to Virtual Destructors and Constructors in C++

  1. chandu says:

    simple and nice explanation.

  2. xxx says:

    nice example 🙂 thank you 🙂

  3. Sanjib says:

    very good explanation…thanks

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s