If I don’t mark a method as virtual, will it be available to a derived class?
If using object a, I make changes to method of base class. Then object b accesses the same method m1() of the base class (which is available to derived class).
Will it print those changed value by object a?
Will they share common method ?
class A
{
public int m(int i)
{
return i * i;
}
}
class B : A
{
}
class C
{
static void Main()
{
A a = new A();
int x = a.m(2); // returns 4
B b = new B();
int y = b.m(4); // 16
}
}
Yes, because the derived class is a type of the base class.
Consider a Mammal class. All mammals breathe, so we would have Mammal.Breathe(). Now consider a Cat class. Since cats are mammals, we would have this as derived from Mammal, then there is already a Cat.Breathe() inherited from Mammal, without any extra work (the “no extra work” bit being one time-saving aspect of OO).
If Mammal.Breathe() was virtual, then we could make it behave differently in the case of Cat.Breathe(). If it’s not virtual, we cannot, though a non-virtual method can call a virtual method, which would make that part of its behaviour overridable.