On the other hand, there is nothing like a virtual constructor. So the destruction of the base pointer (which takes an allocation on derived object!) follows the destruction rule, i.e first the Derived, then the Base. The output changed as following: Base Constructor Called You can learn more about virtuality and virtual base class destructor in this article from Herb Sutter.Ī virtual constructor is not possible but virtual destructor is possible. If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and nonvirtual by doing so, the compiler won't let you call delete on a base class pointer. To sum up, always make base classes' destructors virtual when they're meant to be manipulated polymorphically. In most implementations, the call to the destructor will be resolved like any non-virtual code, meaning that the destructor of the base class will be called but not the one of the derived class, resulting in a resources leak. Type shall be a base class of the dynamic type of the object to beĭeleted and the static type shall have a virtual destructor or the Object to be deleted is different from its dynamic type, the static Since Base's destructor is not virtual and b is a Base* pointing to a Derived object, delete b has undefined behaviour: Because knowing how the virtual table works is not necessary to use virtual. The virtual table sometimes goes by other names, such as vtable, virtual function table, virtual method table, or dispatch table. Now, let's have a look at the following snippet: Base *b = new Derived() The virtual table is a lookup table of functions used to resolve function calls in a dynamic/late binding manner. Here, you'll notice that I didn't declare Base's destructor to be virtual. Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class: class Base
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |