Why do we use virtual and override?

前端 未结 4 1505
情话喂你
情话喂你 2020-12-29 07:28

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         


        
4条回答
  •  清酒与你
    2020-12-29 08:14

    (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).

提交回复
热议问题