Re: C# versus C++ Constructor Problem

Peter Ritchie <[email protected]>
Newsgroups gmane.comp.windows.devel.dotnet.cx
Message-ID <LISTSERV%[email protected]>
It's really bad form to call virtual methods from a constructor, for this
very reason.

C++ and C# implement that slightly differently so you can't rely on a one-
to-one conversion to work the same way.

If I remember correctly, calling virtual methods in a c'tor in C++
is "undefined" meaning you can't rely on it working in a particular way.

On Thu, 22 Jun 2006 11:09:02 -0400, David Thompson
<[email protected]> wrote:

>I'm converting some C++ code to C# and have found something that I'd like
some clarification on.
>If I define the following:
>
>public class Class1
>{
>    public Class1()
>    {
>         initialize();
>    }
>
>    public virtual void initialize()
>    {
>         // Do something
>    }
>
>}
>
>public class Class2 : Class1
>{
>     private SomeOtherClass soc;
>     public Class2() { soc = new SomeOtherClass(); }
>
>     public override void initialize()
>     {
>           base.initialize();
>           soc.SomeFunction();   // error here.
>     }
>}
>
>Now looking at this, in C++ the callstack when creating a new Class2 is:
>
>Class2()
>Class1()
>Class1::initialize()
>
>but in C# the stack becomes:
>Class2()
>Class1()
>Class2.initialize()
>
>Now since Class2's constructor hasn't completed yet, then soc doesn't
exist and an exception is
>thrown because soc doesn't exist yet.
>
>Is there any way to get the C++ behavior in C# or do I have to look at re-
writing the code? I think I
>understand why it happens (dealing with the type information on the
class), but it doesn't seem
>correct. Anybody got some advice?

===================================
This list is hosted by DevelopMentor®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.