Multilevel Inheritence in C#

Posted by Dipu710646 under C# on 11/26/2010 | Points: 10 | Views : 1673 | Status : [Member] | Replies : 1
Hi All I have a multilevel inheritance as below :-

public class OOPs
{
public virtual void Display()
{
Console.WriteLine("A");
}
}
public class B : OOPs
{
public override void Display()
{
Console.WriteLine("B");
}
}
public class C :B
{
public virtual void Display()
{
Console.WriteLine("C");
}
}
public class D : C
{
public override void Display()
{
Console.WriteLine("D");
}
}

I executed following piece of code :-

D d = new D();
OOPs a = d;
a.Display();
Console.ReadLine();

It gave me output as :- B

I am not able to find out the reason ...

Please reply me with the reason.

Thanks,
Dipankar




Responses

Posted by: SheoNarayan on: 11/26/2010 [Administrator] HonoraryPlatinum | Points: 25

Up
0
Down
Very good and interesting question.

I tried your code snippet and it gives exactly what you said and I tried to understand the reason and let me explain.

Try to modify your calling code like below
D d = new D();

d.Display();

OOPs a = d;
a.Display();
Console.ReadLine();


In this case first you will get output as "D"; after that in the debug mode look at the "d" object in QuickWatch. You will notice that C is the base of D, B is the base of C and OOPs is the base of B as displayed below. In the very next line you have specified OOPs a = d that means in the whole inheritance hierarchy, you are limiting the "a" object to refer till B as OOPs comes before B.

D
--- > C
--------- > B
--------------- > OOPs

So when you call Display() method of "a" object then it will call the Display method of B and it will print "B" character.

Hope this will give you an idea how it is working.

Thanks


Regards,
Sheo Narayan
http://www.dotnetfunda.com

Dipu710646, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response