Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Inheritance explanation

Status
Not open for further replies.

iaswnidou

Programmer
Apr 19, 2005
140
0
0
GR
Hello

I have a question on the following console application

class A
{
public void F() { Console.WriteLine("A.F"); }
public virtual void G() { Console.WriteLine("A.G"); }
}
class B: A
{
new public void F() { Console.WriteLine("B.F"); }
public override void G() { Console.WriteLine("B.G"); }
}
class Test
{
static void Main() {
B b = new B();
A a = b;
a.F();
b.F();
a.G();
b.G();
}
}

One object is created here and that is of type B that inherits from A. The A-type variable a is assigned b's reference, so it as well points to the b object...right?
why a.F() results in "A.F" and a.G() in "B.G"?
 
Because you are overriding the original function. The override keyword will take precedence in this case.

Good luck,
Kevin

- "The truth hurts, maybe not as much as jumping on a bicycle with no seat, but it hurts.
 
B.F doesn't override A.F. B.F hides A.F. If you cast a reference to an object from B to A, then A.F is going to called, because it doesn't "know" about hiding.

And then silence smacks right in there...
... And it is loud!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top