I thought that virtualization did not work in the superclass constructor according to the design of OOP. For example, consider the following C # 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(); } } }
This code breaks because when the Descendent object is created, it calls the constructor of the base class, and we call the virtual method in the constructor of the base class, which in turn calls the Derived class method and, therefore, it is reset, because randomValue is not initialized to that time.
Similar code works in C ++ because the PrintRandom call is not redirected to a derived class with IMO, the order in C ++ is something like:
1. call the base class constructor
2. Update V - Table for this class
3. calling the constructor code
My question is, firstly, do I correctly agree that, in accordance with the principles of OOP, virtualization should not / should not work in the constructor of a superclass, and secondly, if I am right, why is the behavior different in all languages. NET (I tested it with C #, VB.NET and MC ++)
Aamir
source share