Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual functions in C#

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();
  1. The derived2 function will be called but the base class function was called , what is the reason for this.
  2. Does .net uses vtables
like image 351
Raghav55 Avatar asked Dec 16 '22 14:12

Raghav55


1 Answers

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.

like image 105
Marc Gravell Avatar answered Jan 02 '23 16:01

Marc Gravell