Both approaches have ups and downs. It's probably best not to call
virtual methods from the constructor.

The reason C# (and Java too) do it this way is probably because of
efficiency. Changing the vtable pointer (what C++ does) isn't possible
in C#/Java because that would confuse the garbage collector.
Additionally, in C++ member fields aren't implicitly initialized so they
would probably contain junk if the constructor was able to call a
virtual method that accesses them (before the base class constructor has
a chance to initialize them). In C#/Java you don't have that problem,
all fields are always initialized to zero/null/false before the
constructor runs.

Regards,
Jeroen

> 
> -----Original Message-----
> From: Stephen Dunn [mailto:[EMAIL PROTECTED] 
> Sent: Thursday, June 19, 2003 15:59
> To: [EMAIL PROTECTED]
> 
> Thanks to FxCop, I've just discovered quite a fundamental 
> difference between
> C++ and C#.
> 
> Check out the following code.
> 
>   class Base
>   {
>     public Base( )
>     {
>       Method( ) ;
>     }
> 
>     public virtual void Method( )
>     {
>       Console.Write("I'm the Base");
>     }
>   }
> 
>   class Derived
>     : Base
>   {
>     public Derived( )
>     {
>       Method( ) ;
>     }
> 
>     public override void Method()
>     {
>       Console.WriteLine("I'm the Derived");
>     }
>   }
> 
> Constructing a Derived object means a call is made to Base's 
> constructor
> which calls Method; not Base's method (as in C++), but 
> Derived's Method.  At
> this point, Derive is only partially constructed.
> When I stumbled over this in C++, I was surprised that the 
> base constructor
> didn't call the derived method.  I soon changed my mind when it was
> explained to me that C++ is implemented this way as 
> unexpected results could
> happen by called Derived's virtual method.
> 
> Would anyone like to comment?  Personally, I feel C++ is 
> correct in this
> instance.
> 
> Cheers,
> 
> Steve
> 

Reply via email to