Click here to Skip to main content
15,905,867 members
Please Sign up or sign in to vote.
3.75/5 (4 votes)
See more:
C#
Class A
{
    Public virtual void WhoAreYou() 
    { 
        Console.WriteLine("I am an A");
    }
}

Class B: A 
{
    Public override void WhoAreYou() 
    { 
        Console.WriteLine("I am a B");
    }
}

Class C: B 
{
    Public new virtual void WhoAreYou()
    { 
        Console.WriteLine("I am a C");
    }
}

Class D: C 
{
    Public override void WhoAreYou()
    { 
        Console.WriteLine("I am a D");
    }
}
  
C c = new D ();
c.WhoAreYou();			// "I am a D"


But when I do the following, it gives this answer. Why ?

A a =  new D ();
a.WhoAreYou();			// "I am a B" !!


My question is : It should have shown : "I am in D"....but it is not. WHY? Please Explain.
Posted
Updated 25-Dec-10 12:38pm
v5
Comments
fjdiewornncalwe 25-Dec-10 18:57pm    
This is actually a pretty good question, so I have updated the code so that it is easier to follow. With clarity this is a great beginner's question to the subtleties of the language.

1 solution

You have used the new keyword while defining the constructor in C.
That 'breaks away' from the original inheritance hierarchy.

The most overridden method that A finds is B's WhoAreYou() as C and D's WhoAreYou() are in a different hierarchy.
 
Share this answer
 
v3
Comments
JF2015 25-Dec-10 4:33am    
Well explained. I spotted the error, but couldn't explain it to the OP :)
Abhinav S 25-Dec-10 4:34am    
Thanks JF2015.
Manfred Rudolf Bihy 25-Dec-10 9:38am    
I'll second JF2015's comment!
fjdiewornncalwe 25-Dec-10 18:39pm    
Excellent. Concise and clear.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900