Tag Archives: virtual destructor

What is the secret of C++ virtual constructors, virtual destructors, and pure virtual functions

C++ virtual constructors, virtual destructors, and pure virtual functions

Virtual functions are also known as dynamic binding. The base type pointer is declared virtually and it will call the proper virtual function dynamically during run time. The derived class will then override the virtual base class function. It must be the exact same signature. Also, dynamic binding will choose the proper function to calling using the address of the virtual table. This will only occur off the pointer handle.
A virtual table is created for every class have one or more virtual functions. The virtual table is usually implemented as an array of function pointers where each function points to a corresponding implementation of the virtual function in the derived class. When an object of the base class is created, it contains a virtual pointer (v – pointer) which point to the start of a v-table. When a virtual function is invoked on this object, the run system resolved it by following the v-pointer to the v-table to invoke the appropriate function. When a derived class is constructed, it will create the virtual table. If the derived class overrides any of the virtual functions in the base class, they will overwritten by the derived class in the virtual table. This is the primary reason why you should never call virtual functions directly from the constructor. The virtual table entries may not have been created by the objects of the derived classes. You may indirectly call base class implementations of those virtual functions.
Classes will contain pure virtual methods so that they ensure the function will be over ridden in the derived class. This is the same as an abstract within Java. Pure virtual functions are created like:
class Boo
{
void foo() = 0;
}
Boo MyBoo; // compilation error

Using virtual destructors, you can destroy objects without knowing their data type. Note that destructors can also be declared as pure virtual functions for abstract classes.

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!