method inheritance question

  • Thread starter Thread starter Jim Owen
  • Start date Start date
J

Jim Owen

In the following code, as I understnad it, the resulting
display would be "I am B", because I have overridden the
constructor in B. However, what if what I really want to
do is display "I am A" followed by "I am B', so that A's
constructor is called, followed by B's constructor? Also,
does it work differently for constructors than it does for
other overridden methods?

public class A : System.Object
{
public A()
{
HelloWorld();
}

virtual public void HelloWorld()
{
Console.WriteLine("I am A");
}
}

public class B : A
{
public B()
{
}

override public void HelloWorld()
{
Console.WriteLine("I am B");
}

public void Main()
{
B MyB = new B();
}
}
 
Not sure what you are looking for, but you can always call your base class
methods from an inherited class (assuming they are marked public or
protected). Adding base.HelloWorld() will make sure the "I am A" actually
gets registered. The inheritance chain has quite a few rules based around
constructors and method inheritance so you'll want to go through the process
of writing a few different examples and run through the C# language
documentation to make sure you understand all of the nuances.

using System;

public class A : System.Object {
public A() {
HelloWorld();
}

virtual public void HelloWorld() {
Console.WriteLine("I am A");
}
}

public class B : A {
public B() {
}

public override void HelloWorld() {
base.HelloWorld();
Console.WriteLine("I am B");
}

private static void Main() {
B MyB = new B();
}
}
 
Jim Owen said:
In the following code, as I understnad it, the resulting
display would be "I am B", because I have overridden the
constructor in B.

No you haven't. Constructors aren't inherited in C#, so can't be
overridden. See
http://www.pobox.com/~skeet/csharp/constructors.html
However, what if what I really want to
do is display "I am A" followed by "I am B', so that A's
constructor is called, followed by B's constructor?

In fact A's constructor *is* called, followed by B's constructor,
because B's constructor is implicitly

public B() : base()
{
}

However, you've only got one call to HelloWorld, and that works
polymorphically from the very start. It's basically a very bad idea to
call virtual methods within a constructor in almost all circumstances.
In the very, very rare situation where it's a good idea, it needs to be
very thoroughly documented, so that people overriding the method know
full well that their method will be called before their constructor has
finished executing, and that therefore they may not have complete state
yet.
 
Back
Top