Exploring Virtual Destructors in C++/CLI

This article discusses what virtual methods are, why constructors cannot be virtual and why virtual destructors are needed and the pitfalls if destructors are not defined virtual in some scenarios. The concepts are discussed in a lucid language with plenty of code examples to illustrate the concepts.

A constructor is a method that has the same name as the name of the class and is invoked at the time the class is instantiated. On the contrary, a destructor is a method that has the same name as the class name but is prefixed with a tilde sign.

Here is an example that illustrates how a constructor and a destructor look.

class Test
{
Test()
{
}
~Test()
{
}
};

Note that in C++ you cannot have access modifiers for constructors. Constructors in C++ cannot be non-static also.

Virtual Methods

Now, what is a virtual method? Well, the virtual keyword is prefixed to a method of a class to signify that the method is virtual. A virtual method is used to implement run-time polymorphism.

We now have a virtual method for the class Test shown below.

class Test
{
Test()
{
}
virtual int Sample()
{
//Some code
}
~Test()
{
}
};

Note that for classes that have virtual methods, you would have a virtual table in memory. Virtual tables are used to map the virtual methods at runtime. If a class has n virtual methods, there would be one and only one virtual table in memory where the mapping information of all the n virtual methods would be defined. Virtual tables are created at the time the constructor of the class is invoked. So, you cannot have a virtual constructor as at the time the constructor is invoked, virtual table for the class is not available in memory.

When you have a virtual method defined in a class, you have a virtual pointer made available to you that points to the base address of the virtual table in memory. Consider the following code.

class Base
{
public:
virtual void Sample()
{
printf("Hello from Base");
} 
};
class Derived: public Base
{
public:
virtual void Sample()
{
printf("Hello from Derived");
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Base *b = new Derived;
b->Sample();
getchar();
return 0;
}

When you execute the above code, the message "Hello from Derived" is displayed on the screen. Now, if you omit the virtual keyword from each of the classes, i.e., the Base and also the Derived classes, you would see that the message "Hello from Base" is displayed.

class Base
{
public:
void Sample()
{
printf("Hello from Base");
} 
};
class Derived: public Base
{
public:
void Sample()
{
printf("Hello from Derived");
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Base *b = new Derived;
b->Sample();
getchar();
return 0;
}

The reason is that when a base class pointer points to a derived class instance and a method on the instance is called, the base version would always be invoked as the type of the pointer would be considered. However, if the method is defined as virtual in both the base and the derived classes, the context of the pointer would be considered. Hence the result.

Why do we Need Virtual Destructors?

A destructor can be virtual. Why should a destructor be virtual? Let's consider a scenario in which there are two classes, a base class called Base and a derived class called Derived. Now, constructors are invoked in the order of inheritance and destructors are invoked in the reverse order of inheritance. So, in this example, the constructor of the Base class would be invoked followed by the Derived class constructor. So, the Derived class destructor would be invoked followed by the Base class destructor at the time when the object goes out of the scope or is destroyed.

Now, suppose you create an instance of the Derived class using a Base class pointer as we did earlier in this article. When you delete the pointer object using the delete keyword, the destructor of the Base class would be called and the destructor of the Derived class would simply be ignored.

The reason is that the destructor is simply another method and so when the delete keyword is used to delete the pointer instance, the type of the pointer would be considered. And, because the type of the pointer is of type Base, the destructor of the Base class would only be invoked. This might create memory leaks as the instance of the derived class would still remain in memory even after the pointer instance has been deleted/destroyed from memory. To avoid this potential memory leak, virtual destructors are used.

Summary

Virtual destructors in C++ are used to avoid memory leaks when your class contains unmanaged code, i.e., contains pointers or object handles to files, databases or other external objects. In this article we explored virtual methods and virtual destructors in C++. Happy reading!

About the Author

Joydip Kanjilal is a Microsoft Most Valuable Professional in ASP.NET, speaker and author of several books and articles. He has over 16 years of industry experience in IT with more than 10 years in Microsoft .NET and its related technologies. Joydip was selected as MSDN Featured Developer of the Fortnight (MSDN) a number of times and also as Community Credit Winner. His books include the Entity Framework Tutorial, Sams Teach Yourself ASP.NET Ajax in 24 Hour, and ASP.NET Data Presentation Controls Essentials. You can follow him on Twitter (@joydipkanjilal) or see more about him on LinkedIn at http://in.linkedin.com/in/joydipkanjilal



Related Articles

Comments

  • No depth analysis

    Posted by Sk patra on 01/30/2014 12:00am

    Is this the reason why constructor are not made virtual.If Creation time of virtual table is the only reason, then I think its not. The constructor are not made virtual to support a strong OOPS concept only( may be constructor call will be recursive from base to derived and derived to base, or to support a virtual concept which operates on a pure object type(constructor) ).

    Reply
  • Reply from author

    Posted by Joydip Kanjilal on 01/14/2014 06:52am

    Hello, What I have mentioned is based on the earlier versions of C++, i.e., Native C++. Please note that C++ was not intended to have static constructors in the beginning. Static constructors were introduced to C++ much later. Also access modifiers for constructors were introduced much later in C++ - it wasn't available to the language initially. Thanks, Joydip

    • C++/CLI is NOT C++

      Posted by Ovidiu Cucu on 02/07/2014 05:13am

      First, please note that C++ and C++/CLI (aka "managed C++") are two DIFFERENT programming languages. If you are talking about C++ (actual or older), then NO, there are NOT static constructors in C++. Never was and probably, will be never static. Even the last C++ standard, ISO/IEC 14882:2011 (aka C++11) specify it very clear "12.1 Constructors: a constructor shall not be virtual or static." If you are talking about C++/CLI, then the article is off-topic here. Should be me moved in another CG section, dedicated to C++/CLI (or managed C++). Anyway, to avoid misleading others, PLEASE change the title to clearly show that is about C++/CLI (or managed C++) and not about C++. Regards, Ovidiu

      Reply
    Reply
  • Is it a typo?

    Posted by Ovidiu Cucu on 01/14/2014 03:01am

    "...Constructors in C++ cannot be non-static..." In C++ programming language, ALL the constructors ARE non-static. See http://codexpert.ro/blog/2013/02/26/dispelling-common-c-myths-static-constructors/

    Reply
  • Seriously?

    Posted by Marius Bancila on 01/06/2014 08:18am

    "Note that in C++ you cannot have access modifiers for constructors. Constructors in C++ cannot be non-static also." Really? You can't declare constructors as private or protected? Where did you learn that? Constructors cannot be non-static, means they can are only static? What?! "used to delete the pointer instance" What's a pointer instance? "Virtual destructors in C++ are used to avoid memory leaks when your class contains unmanaged code" What else than unmanaged.native code can a C++ function contain?

    Reply
  • Virtual Destructor

    Posted by manisha on 01/03/2014 03:37am

    Hello sir, Article is superb .. Language is simple and explanation is very good manisha

    • VC++ developer

      Posted by Victor on 01/14/2014 06:26am

      Is "superb" now an equivalent to "wrong"? See the commeny posted by Marius Bancila...

      Reply
    Reply
  • Full of errors

    Posted by Marius on 12/28/2013 07:09am

    What is this nonsense? Constructors cannot have access modifiers and cannot be non-static? That means they are always static? What about classes that contain unmanaged code? This is C++, for googness sake, it's all unmanaged code.

    Reply
  • Probably it's just a typo

    Posted by Ovidiu Cucu on 12/27/2013 06:50am

    "Constructors in C++ cannot be non-static" In contrary, in C++ constructors cannot be static. Please have a look at this article: http://codexpert.ro/blog/2013/02/26/dispelling-common-c-myths-static-constructors/ Ovidiu

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds