Note that there are some explanatory texts on larger screens.

plurals
  1. POVirtualization in Super Class Constructor
    primarykey
    data
    text
    <p>I was of the opinion that virtualization doesnt work in the super class constructor as per the design of OOP. For example, consider the following C# code. </p> <pre><code>using System; namespace Problem { public class BaseClass { public BaseClass() { Console.WriteLine("Hello, World!"); this.PrintRandom(); } public virtual void PrintRandom() { Console.WriteLine("0"); } } public class Descendent : BaseClass { private Random randomValue; public Descendent() { Console.WriteLine("Bonjour, Monde!"); randomValue = new Random(); } public override void PrintRandom() { Console.WriteLine(randomValue.NextDouble().ToString()); } public static void Main() { Descendent obj = new Descendent(); obj.PrintRandom(); Console.ReadLine(); } } } </code></pre> <p>This code breaks because when the object of Descendent is made, it calls the base class constructor and we have a virtual method call in Base Class constructor which in turn calls the Derived class's method and hence, it crashes since randomValue is not intialized by that time.</p> <p>A similar code works in C++ because the call to PrintRandom is not routed to the derived class since IMO, the order in C++ is something like:</p> <p><br>1. call for base class constructor <br>2. Update V - Table for this class <br>3. call the constructor code</p> <p>My Question is that firstly whether I am right that as per OOP principles, virtualization shouldn't/doesn't work in the super class constructor and secondly if I am right, then why the behavior is different in all .NET languages ( I have tested it with C#, VB.NET and MC++)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload