tags:

views:

131

answers:

3
Class A
{
virtual m1()
  {
  console.writeline("m1() in A");
  }

}
Class B
{
 override m1()
    {
     console.Writeline("m2() in B");

     }

}

class C:B
{


 override m1()
    {
     console.Writeline("m2() in c");

     }

}
class D
{
main()
{
A a=new A();
a.m1();       ///m2() in B

B b=new B();
b.m1();      ///m2() in B

C c=new C();
c.m1()       /////  what here will be called please le me know

}

}

also let me now can we use virtual and override together

+1  A: 

Result will be a bunch of compile errors I guess..

But if you get it compiled, and run it, the result will be:

m1() in A

m2() in B

m2() in c

Arcturus
A: 

First of all you have not added inheritance to class B. You should define it like:Class B : A The result is m2() in c Define each function which you want to override as virtual in parent class and use override keyword in your child classes to override the parent class's method. Just as you did in your example.
P.S. `a.m1();' would return m1() in A
Try this:

class A
{
  virtual void m1()
  {
  console.writeline("m1() in A");
  }
}
class B:A
{
  override m1()
  {
    console.Writeline("m2() in B");
  }
}
class C:B
{
  override m1()
  {
    console.Writeline("m2() in c");
  }
}
class D
{
  main()
  {
    A a=new A();
    a.m1();       ///m1() in A

    B b=new B();
    b.m1();      ///m2() in B

    C c=new C();
    c.m1()       /////  what here will be called please le me know
  }
}
Kamyar
+2  A: 

This does not compile, because:

  • class is not written with a Capital letter: class
  • console.writeline is written as: Console.Writeline
  • class B overrides a method that does not exist on object

C# is a case sensitive language!!!

virtual is used to declare a method (for the first time) that can be overruled/inherited/override in a child class.

overrides indicates that your child class overrides a virtual method from the parent, on purpose. So that you cannot do this accidentally.

GvS