This is a mirror of official site: http://jasper-net.blogspot.com/

9 Rules about Constructors, Destructors, and Finalizers

| Tuesday, May 4, 2010
Overview

First, this writing concentrates of and compares between three programming languages, C#, C++/CLI, and ISO/ANSI C++. It discusses 9 rules that every developer should keep in mind while working with constructors, destructors, and finalizers and class hierarchies:

   * Rule #1: Contrsuctors are called in descending order
   * Rule #2: In C# lexicology, a destructor and a finalizer refer to the same thing
   * Rule #3: Destructors are called in ascending order
   * Rule #4: Finalizers are a feature of GC-managed objects only
   * Rule #5: You cannot determine when finalizers would be called
   * Rule #6: MC++ differs between destructors and finalizers
   * Rule #7: In MC++ and classic C++, you can determine when destructors are called
   * Rule #8: In MC++, destructors and finalizers are not called together
   * Rule #9: Beware of virtual functions in constructors

Rule #1: Constructors are called in descending order

   Rule #1: Constructors are called in descending order; starting from the root class and stepping down through the tree to reach the last leaf object that you need to instantiate. Applies to C#, MC++, and ANSI C++.

Let's consider a simple class hierarchy like this:

class BaseClass
{    

public BaseClass()    
{        
Console.WriteLine("ctor of BaseClass");    
}
}

class DerivedClass : BaseClass
{    

public DerivedClass()    
{        
Console.WriteLine("ctor of DerivedClass");    
}
}

class ChildClass : DerivedClass
{    

public ChildClass()    
{        
Console.WriteLine("ctor of ChildClass");    
}
}

ChildClass inherits from DerivedClass, and DerivedClass, in turn, inherits from BaseClass.

Read more: C# Corner

Posted via email from jasper22's posterous

0 comments: