public class Base1
{
public virtual void f()
{
Console.WriteLine("Base1.f()");
}
}
public class Derived1 : Base1
{
// Hides Base1.f() because 'override' was not specified
public new virtual void f()
{
Console.WriteLine("Derived1.f()");
}
}
public class Derived2 : Derived1
{
// Overrides Derived1.f()
public override void f()
{
Console.WriteLine("Derived2.f()");
// Call base method
base.f();
}
}
class Program
{
static void Main(string[] args)
Base1 ob1 = new Derived1();
ob1.f();
Base1 ob2 = new Derived2();
ob2.f();
Derived1 ob3 = new Derived2();
ob3.f();
Derived2 ob4 = new Derived2();
ob4.f();
}
}
// Calls Derived2.f() because Derived2 overrides Derived1().f()
Derived1 ob3 = new Derived2();
ob3.f();
it was expecting that the
Base1 ob2 = new Derived2();
ob2.f();
The method slot used by static analysis during compilation depends on the type of the variable (or expression), not the actual object. The variable ob2
is typed as Base1
, so the Base1
method slot is used. And then the correct override is selected based on the typed (essentially vtable on that slot). So the base function is used.
To use the derived2 function, the variable (or expression) must be typed as Derived1
or a subclass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With