16

Why do we use override and virtual if it gives the same effect when we dont use override and virtual?

example 1:

class BaseClass
{
    public virtual string call()
    {
        return "A";
    }
}

class DerivedClass : BaseClass
{
    public override string call()
    {
        return "B";
    }
}

output : B

Example 2:

class BaseClass
{
    public string call()
    {
        return "A";
    }
}

class DerivedClass : BaseClass
{
    public string call()
    {
        return "B";
    }
}

and the output is still the same:

output : B

to run the test:

class Program
{
    static void Main(string[] args)
    {
        DerivedClass dc = new DerivedClass();
        Console.WriteLine(dc.call());
        Console.ReadKey();
    }
}

Does the compiler add virtual and override automatically at compile time?

I would be pleased if someone would explain to me the reason for using virtual and override.

Racooon
  • 1,468
  • 2
  • 10
  • 28
  • 1
    You will get a different result if you canst derivedClass to base class before calling add: 1 => 2 and 2 => 1 – Peter Oct 24 '11 at 12:29
  • @CD.. there is no duplicate, its about the "override and virtual" – Racooon Oct 24 '11 at 12:32
  • 2
    it would really be a lot nicer to post examples that.... compiled. – Marc Gravell Oct 24 '11 at 12:34
  • @VuralAcar: Although the question is slightly different, it's the same principle. You are just misunderstanding the difference between polymorphism and method hiding. – Roman Oct 24 '11 at 12:35
  • @MarcGravell I have just edited. – Racooon Oct 24 '11 at 12:44
  • 3
    Your test (obviously) does not demonstrate the difference. Change the line to "BaseClass dc = new DerivedClass();" and try again. Now is there a difference? – Eric Lippert Oct 24 '11 at 14:38

4 Answers4

21

(note, I'm quietly ignoring the compile errors)

Now do:

BaseClass obj = new DerivedClass();
Console.WriteLine(obj.call());

Without virtual, this will print A, when actually a DerivedClass should be writing B. This is because it has simply called the BaseClass implementation (since obj is typed as BaseClass, and no polymorphism is defined).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Here is a nice link on this (probably nicer out there but it was the first I found when googling implicit hiding) http://geekswithblogs.net/BlackRabbitCoder/archive/2010/06/24/c-fundamentals-beware-of-implicit-hiding.aspx – David Hall Oct 24 '11 at 12:31
  • It prints the same, and it doesnt matter if you use override and virtual. I think the compiler adds it at the compile time. – Racooon Oct 24 '11 at 12:54
  • 3
    @Vural look very carefully at the difference between my scenario and yours. Now change your code to `BaseClass bc = new DerivedClass(); Console.WriteLine(bc.call());`. To emphasise: no ***it does not*** add this automatically at compile-time; merely, you are testing something different. – Marc Gravell Oct 24 '11 at 12:58
  • How I am testing something different? Its very clearly,what I am trying to do? 2 Classes with virtual and override and 2 classes without return the same result. You create an Object Of BaseClass and initialize it with DerivedClass. Thats actually not what I want to do. Did I understand you wrong? – Racooon Oct 24 '11 at 14:17
  • 5
    @Vural becuase that is *when it matters*. If you aren't using polymorphism, then yes: they will show the same thing. The difference is that `virtual` supports abstraction and [substitution](http://en.wikipedia.org/wiki/Liskov_substitution_principle). You ask "why do we use {these}" - and I'm saying: **to support this scenario**. A lot of times, we don't know the concrete/final type - we only know the base-type. For example, a `Control` in winforms, or a `Page` in ASP.NET. – Marc Gravell Oct 24 '11 at 14:52
  • @Marc Gravell can you please explain real world scenario where and when do we need method overriding? –  Oct 16 '17 at 10:51
  • 1
    @TAHASULTANTEMURI that would be the entire cornerstone of polymorphism. Basic example: you have a class and want to change the text representation (override `ToString()`) or how equality works (override `Equals()` and `GetHashCode()`). More complex example: you're implementing a custom ADO.NET provider, so you subclass `DbConnection`, `DbParameter`, `DbDataReader` etc and override various methods to add your implementation. – Marc Gravell Oct 16 '17 at 12:41
  • Thankyou very much sir! –  Oct 16 '17 at 12:58
5

Virtual and override are a base mechanism of inheritance in object oriented programming. This is perhaps the most important thing to understand when you use classes in a language like C# or Java.

http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)

Inheritance allow you to reuse code adding new fields, properties and methods or replacing methods and properties of previously defined classes.

Virtual and Override allow you to replace the content of a method, and when i say replace, i say replace.

I would propose you a nice example.

public class MyClassEnglish
{
    public virtual string SomethingToSay()
    {
        return "Hello!";
    }

    public void WriteToConsole()
    {
        Console.WriteLine(this.SomethingToSay());
    }
}

public class MyClassItalian :
    MyClassEnglish
{
    public override string SomethingToSay()
    {
        return "Ciao!";
    }
}

int main()
{
    MyClassItalian it = new MyClassItalian();

    it.WriteToConsole();
}

If you omit virtual and override, MyClassItalian will print out "Hello!" and not "Ciao!".

In your example you show a Shadowing technique, but the compiler should give you a warning. You shoul add the "new" keyword if you want to hide a method in a base class. Hiding a method is not overriding! Is just hiding.

One possible use that comes into my mind is that it can be used when you need some kind of optimization for example.

public abstract class MySpecialListBase
{
    public int Count()
    {
        return this.GetCount();
    }

    protected abstract int GetCount();
}

public sealed class MySpecialArrayList : MySpecialListBase
{
    int count;

    public new int Count()
    {
        return this.count;
    }

    protected override int GetCount()
    {
        return this.count;
    }
}

Now... You can use MySpecialListBase in all your code, and when you call the Count() it will call the virtual method GetCount(). But if you use just MySpecialArrayList it will call the optimized Count() that is not virtual and that just return a field, increasing performances.

// This works with all kind of lists, but since it is a more general purpose method it will call the virtual method.    
public void MyMethod(MySpecialListBase list)
{
    Console.WriteLine(list.Count());
}

// This works only with MySpecialArrayList, and will use the optimized method.
public void MyMethod(MySpecialArrayList list)
{
    Console.WriteLine(list.Count());
}
Salvatore Previti
  • 8,956
  • 31
  • 37
0

Best example I can think of where this is useful is when you create your own object(class) and you have to add a list of that object to a combobox.

When you add your object to the combobox you want to be able to control what text is displayed for each item. Object.toString is a virtual method. http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx and because of this you can override that method and set .toString to display the correct information about your object by overriding it.

public MyClass()
{
     private int ID;
     public override string ToString()
     {
         return "My Item:" + ID;
     }
}
Gage
  • 7,365
  • 9
  • 47
  • 77
0

Method Overriding:

Where you define or implement a virtual method in a parent class and then replace it in a descendant class.

When you decide to declare a method as virtual, you are giving permission to derived classes to extend and override the method with their own implementation. You can have the extended method call the parent method's code too.

In most OO languages you can also choose to hide a parent method. When you introduce a new implementation of the same named method with the same signature without overriding, you are hiding the parent method.

C# Overriding In C#, you specify a virtual method with the virtual keyword in a parent class and extend (or replace) it in a descendant class using the override keyword.

Use the base keyword in the descendant method to execute the code in the parent method, i.e. base.SomeMethod().

Syntax Example:

class Robot
{
  public virtual void Speak()
  {
  }
}

class Cyborg:Robot
{
   public override void Speak()
   {
   }
}

Override Details You cannot override a regular non-virtual method, nor a static method. The first version of the parent method must be virtual or abstract. You can override any parent method marked virtual, abstract, or override (already overridden). The methods must have the same signature. The methods must have the same visibility (the same access level). Use the base keyword to refer to the parent class as in base.SomeMethod(). C# Override Example The following code snippet demonstrates using virtual and override to override a parent method in a descendant class.

using System;

class Dog
{
   public virtual void Bark()
   {
       Console.WriteLine("RUFF!");
   }
}

class GermanShepard:Dog
{
    public override void Bark()
    {
       Console.WriteLine("Rrrrooouuff!!");
    }
}

class Chiuaua:Dog
{
    public override void Bark()
    {
         Console.WriteLine("ruff");
    }
}
class InclusionExample
{
     public static void Main()
     {
        Dog MyDog=new Dog();    
        MyDog=new GermanShepard();
        MyDog.Bark(); // prints Rrrrooouuff!!

        MyDog=new Chiuaua();
        MyDog.Bark(); // prints ruff;
    }
}

Hiding a Method with New Use the new keyword to introduce a new implementation of a parent method (this hides the parent method). You can hide a method without using new but you will get a compiler warning. Using new will suppress the warning.

The new and override modifiers have different meanings. The new modifier creates a new member with the same name, signature, and visibility and hides the original member. The override modifier extends the implementation for an inherited member and allows you to implement inheritance-based polymorphism.

Avoid Introducing New Members: Sometimes there are clear reasons to introduce a new method with the same name, signature, and visibility of a parent method. In those clear cases, introducing a new member is a powerful feature. However, if you do not have a clear reason, then avoid introducing a new version of a method by naming the new method something unique and appropriate.

class Robot : System.Object
{
  public void Speak()
  {
    MessageBox.Show("Robot says hi");
  }
}

class Cyborg : Robot
{
  new public void Speak()
  {
    MessageBox.Show("hi");
  }
}

Calling the Base Class Version A common task In OO is to extend a method by first executing the parent method code and then adding code. Use the base keyword to refer to the parent class as in base.SomeMethod().

class Robot : System.Object
{
    public virtual void Speak()
    {
       MessageBox.Show("Robot says hi");
    }
}
class Cyborg : Robot
{
  public override void Speak()
  {
      base.Speak(); 
      MessageBox.Show("hi");
  }
}
Glory Raj
  • 17,397
  • 27
  • 100
  • 203