Virtual Functions C#

前端 未结 3 683
情深已故
情深已故 2020-12-30 19:07

I understand what a virtual function is. But what I don\'t get is how do they work internally?

class Animal
{
    virtual string Eat()
    {
        return @         


        
3条回答
  •  执念已碎
    2020-12-30 19:16

    In C#, derived classes must provide the override modifier for any overridden method inherited from a base class.

    Animal _animal = new Human();
    

    It's not just the Human object got constructed. They are two sub-objects. One is Animal sub-object and the other is Human sub-object.

    Console.WriteLine(_animal.Eat());
    

    When made the call to _animal.Eat();, the run time checks whether the base class method ( i.e., Eat() )is overridden in the derived class. Since, it is overridden, the corresponding derived class method is called. Hence the output -

    Eat like a Human
    

    But, in case of -

    _animal = new Dog();
    Console.WriteLine(_animal.Eat());
    

    In the Dog, there is no Eat() overridden method in the derived class Dog. So, base class method itself is called. Also this method of checking is done because in the base class, Eat() is mentioned as virtual and calling mechanism is decided at run-time. To sum up, virtual calling mechanism is a run-time mechanism.

提交回复
热议问题