Question on inheritance

  • Thread starter Thread starter Pete Davis
  • Start date Start date
P

Pete Davis

Your getting Parent.Meth() precisely because it's not virtual. If it were,
then it would call down to the child class. Since it's not virtual, and
you're casting it to parent, it's executing the parent method.

Pete
 
Hello,

I have a question on inheritance, please see the code below for reference:

****************************************************************

using System;

public class Parent
{
internal int id;
public Parent(int id)
{
this.id = id;
}

public void Meth( )
{
Console.WriteLine("Hello from Parent.Meth, id={0}", id);
}
}

public class Child : Parent
{
public Child(int id) : base(id) // call base constructor
{
}

public new void Meth( )
{
Console.WriteLine("Hello from Child.Meth, id={0}", id);
}
}

public class Executer
{
public static void Main( )
{

Parent p = new Parent(1); p.Meth();
Child c = new Child(2); c.Meth();

Parent pp = new Parent(3); pp.Meth();
Parent cc = new Child(4); cc.Meth();

}
}
****************************************************************

the cc.Meth() call returns "Hello from Parent.Meth, id=4", that is, the
parent method is called, though variable cc was assigned Child object. I
realize, that if I'd mark Meth virtual in Parent class, and mark child Meth
with override, I'd get "Hello from Parent.Meth, id=4" instead. But, in the
first case, where did the Child.Meth get? Is is no more accessible due to
type conversion that happened because variable cc is marked as type Parent?
I have hard time understanding why I'd have to use "virtual" and "override",
if I can simply leave the parent class method as is, and define child method
using "new", and I only have to assign child object instances to child type
variables (vs parent type).

Thanks,

Pavils
 
?I realize, that if I'd mark Meth virtual in Parent class, and mark
child Meth with override, I'd get "Hello from Parent.Meth, id=4"
instead.?

You would not. Try it and only then you will realize. :)

with regards,


J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- http://www.411asp.net/func/search?
qry=Ravichandran+J.V.&cob=aspnetpro
- http://www.southasianoutlook.com
- http://www.MSDNAA.Net
- http://www.csharphelp.com
- http://www.poetry.com/Publications/
display.asp?ID=P3966388&BN=999&PN=2
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com
 
Back
Top