Valerie Meunier

Valerie Meunier

  • NA
  • 693
  • 83.5k

question about benefits of virtual / override

Jun 9 2022 3:11 PM

Hi, i have a question about the sense of using virtual / override. Look at this code.

using System;
class Animal  
{
    public void AnimalSound()
    {   Console.WriteLine("The animal makes a sound");  }
}

class Cat : Animal 
{
    public void AnimalSound()
    {  Console.WriteLine("The cat says: miauw");  }
}


class Program
{
    static void Main(string[] args)
    {
        Animal myAnimal = new Animal();  
        Animal myCat = new Cat();
        myAnimal.AnimalSound();
        myCat.AnimalSound();
    }
}


This gives 2 times: The animal makes a sound. It's normal. The solution is to make method AnimalSound() in class Animal virtual and override in class Cat.

But why not just doing this:  Cat myCat = new Cat(); (instead of Animal myCat = new Cat();) ? Then it's solved. Isn't it easier than using virtual and override? What are the benefits in this case to use virtual/override?
Thanks
V.
 


Answers (2)