none
Virtual Constructor and virtual Destructor

All replies

  • Virtual constructors are sort of an oxymoron in my opinion.  A virtual method is one that CAN be overridden in a derived class but does not have to be.  If it is not then the base class method can be used instead.  Constructors are not virtual in the sense that a derived class must define all the overloads they want for a constructor (nor can they have the virtual keyword).  There is no such thing as "inheriting a base class constructor".  However C# guarantees that for every derived class constructor a base class constructor will be called first.  Normally this is the default constructor however you can use the base keyword to call a specific constructor from the base class.  This constructor-chaining concept is prevalent throughout OO languages.  In C# the base class is fully constructed before the derived class is constructed but this is not guranteed in other languages.

    Virtual destructors are different.  Some languages (like C++) do not make destructors virtual by default.  If a destructor is not virtual then when the object is destroyed it might or might not call the correct destructor.  It depends on how the object is referenced.  For example the following code will not call Derived's destructor:

    class Base
    {
       ~Base ( ) { }
    };
    class Derived : public Base
    {
       ~Derived() { }
    };

    //In code
    Base* pBase = new Derived;
    delete pBase;

    The reason is the same as for all non-virtual methods.  A non-virtual method is "attached" to the method call at compilation time since it can't change.  With virtual methods the "attachment" occurs at runtime when the type of the object can be examined.  As a result most base classes in C++ mark their destructors as virtual to ensure that deletion works properly.

    C# however says that all destructors (actually finalizers) are virtual so no keyword is needed and finalization happens appropriately depending on type.  For more information on this do a Google search for "Virtual Constructor" and C# or "Virtual Destructor" and C++.

    Michael Taylor - 6/26/06

    Monday, June 26, 2006 12:41 PM
  • As Michael said, there is no such thing as a "Virtual constructor".  Generally, when people use the term, they are refering to a Factory method, or a Clone method.
    Monday, June 26, 2006 5:58 PM
  • virtual is usually used to avoid leaks.

    As michael said, we need to make base class deistructor virtual, so that when we call,

     

    delete pBase;

     

    it first calls the derived class destructor then base class destructor.

     

    Using virtual in base class destructor to avoid these kind of bugs is considered as good programming...

    Wednesday, July 04, 2007 5:09 AM