No Virtual constructors but virtual destructor

20,892

Solution 1

  • There is no point in virtual constructor - you declare exactly what type is created, and it is well known in compile time. The compiler do not need [and actually cannot, since the dynamic dispatch is based on information which is created only after the object was created]. So there are no virtual constructors.
  • Virtual destructors are important to prevent memory leaks, and monitor the system. Assume you have A* a = new B; [B inherits from A], and you later delete a; - the compiler has no way of knowing a is a B [in the general case], and will invoke A's destructor - if it wasn't virtual, and you might get a memory leak, or other faults.
  • Using virtual destructor - you ensure that B's destructor is invoked, since a B object is being destroyed.

Solution 2

Virtual destructors are needed because at destruction time, you don't always know what type you're dealing with:

Base *make_me_an_object()
{
    if (the_moon_is_full())
        return new Derived();
    else
        return new Base();
}

int main()
{
    Base *p = make_me_an_object();
    delete p;
}

The delete in the above program's main doesn't know whether its p points to a Base or a Derived object, but if the Base destructor is virtual (as it should be), then delete can use *p's vtable to find the right destructor.

By contrast, at construction time, you always know what kind of object you're creating. (And in case you don't, then you can create a factory or "virtual constructor" that does know.)

Share:
20,892
Parag
Author by

Parag

Kas kay?

Updated on July 05, 2022

Comments

  • Parag
    Parag almost 2 years

    If we dont have virtual constructors then why we have virtual destructors? Can constructors also be virtual?

  • devsda
    devsda almost 12 years
    I didn't understand the first point . can you elaborate it, please.
  • amit
    amit almost 12 years
    @jhamb: When you invoke a constructor - it is something like new MyClass;. The dynamic type and the static type of the created object - are exactly the same, the real concrete object.