3

Possible Duplicate:
Virtual member call in a constructor

In C#, is it safe to call virtual method from constructor? What does the language specification say? Please quote from the spec as well. By safe, I mean would it call the implementation of the derived class?

This doubt exists in my mind, because in C++, it is not safe to call virtual function from constructor.

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Alright! A duplicate exists. Voted for close then! – Nawaz Jun 24 '11 at 04:27
  • 1
    Why do you define "safe" as calling the implementation of the derived class? One could make the reasonable argument that C++'s technique (of calling the method implementation based on what parts of the class have been initialized) is the safer choice. – Eric Lippert Jun 24 '11 at 06:27
  • @Eric: One could make that argument if I leave that that vague! – Nawaz Jun 24 '11 at 06:32

2 Answers2

6

You can do it, but you shouldn't. I think C# even gives you a warning for it.

It becomes very dangerous when the function has been overridden by a derived class, because you're now calling into that function before the derived class's constructor has been called.

Shirik
  • 3,631
  • 1
  • 23
  • 27
  • In C++, the derived class implementation is NOT called, for exactly that reason. – Ben Voigt Jun 24 '11 at 04:25
  • 2
    In C++ memory might not be fully initialized, but that's not an issue in C#. – Gabe Jun 24 '11 at 04:27
  • @Gabe: Memory initialized is not the same as the invariants being established. – Ben Voigt Jun 24 '11 at 12:00
  • 1
    @Ben: That's very true. However, since the memory is guaranteed to be initialized, you can reliably detect that your invariants may not hold and act properly. I'm not saying it's a good idea, but you can write reliable code that does it. – Gabe Jun 24 '11 at 13:42
  • @Gabe: anyway, in C++, the derived class memory isn't fully initialized, which is why the derived version of the function isn't called. The version which is called matches a base subobject whose memory is fully initialized (all subobjects of the active dynamic type have been constructed). – Ben Voigt Jun 24 '11 at 13:44
1

It's not safe, since the virtual function would be called before the matching constructor has had a chance to establish the class invariants.

In contrast, it IS safe in C++ -- the function which is called is called during the matching constructor, not before.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720