Re: C# versus C++ Constructor Problem
Stoyan Damov <[email protected]>
| Newsgroups | gmane.comp.windows.devel.dotnet.cx |
|---|---|
| Message-ID | <[email protected]> |
I'll just add that you should never call virtual methods in destructors too (in C++). On 6/22/06, Peter Ritchie <[email protected]> wrote: > BTW, you may be interested in the following references: > http://blogs.msdn.com/abhinaba/archive/2006/02/28/540357.aspx > http://blogs.msdn.com/scottwil/archive/2005/01/14/353177.aspx > http://www.artima.com/cppsource/nevercall.html > > As well as Scott Meyer's Effective C++; he discusses calling virtual > methods in c'tors (and why you shouldn't) > > 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(r) http://www.develop.com > > View archives and manage your subscription(s) at http://discuss.develop.com > -- Cheers, Stoyan =================================== This list is hosted by DevelopMentor® http://www.develop.com View archives and manage your subscription(s) at http://discuss.develop.com