C# Inheritance lesson

Today there was a pretty active thread on the Advanced DotNet mailing list entitled: "Partially constructed objects in C#"

http://discuss.develop.com/archives/wa.exe?A1=ind0306c&L=advanced-dotnet

I found had noticed this just the other day when "playing" with inheritance and was surprised coming from a C++ background.  I had to try it out in C# and C++ just to make sure.

I created a BaseClass in C# and C++ with a constructor and a single virtual method f1();

The BaseClass CTOR prints an I am here message and then calls f1()

A second class is derived from BaseClass and overrides f1()

In C# the output is:

BaseClass.CTOR
DerivedClass.f1
DerivedClass.CTOR

and in C++ I get:

BaseClass.CTOR
BaseClass.f1
DerivedClass.CTOR

I suppose this shouldn't have been surprising if I had RTFB but ...

The thread is interesting.  C# and Java have the same behavior.  There was argument as to which is a better way, the C++ or the C#.  It really doesn't matter because each language is  the way it is.  But I hadn't really thought about calling virtual methods from the construct as being unsafe.

Learn every day.  My motto.

 

Published Thursday, June 19, 2003 7:55 PM by cloudycity

Comments

# re: C# Inheritance lesson

From my past C++ background I think that the problem is that if you want to obtain the same behaviour in C++ you need to declare virtual the f1 method in the base class.

It's 3 year that I don't write code in C++ so please try it.

Friday, June 20, 2003 7:05 AM by Lorenzo Barbieri

# re: C# Inheritance lesson

Sorry I posted a wrong comment because I've read the blog entry when another person was talking to me and I missed that the f1 method was already virtual.

Sorry.

Friday, June 20, 2003 7:07 AM by Lorenzo Barbieri

Leave a Comment

(required) 
(required) 
(optional)
(required)