Virtual functions, calling inherited class. Quicky.

  • Thread starter Thread starter Claire
  • Start date Start date
C

Claire

I'm having real brain failure today.
I've done this lots of times with constructors but not with virtual methods
and the compiler complains because Ive put the :base(foo) after the function
header.
I want to call the BaseResult class to let it write shared data before I let
the derived class write its own data. What am I doing wrong please.

public abstract class BaseResult

{

public virtual void Write(System.IO.BinaryWriter binarywriter)

{

WriteMyData()

}

}



public class MimicResult : BaseResult

{

public override void Write(System.IO.BinaryWriter binarywriter) :
base(binarywriter) /*compiler complains*/

{

// Do I do something here?


}

}
 
Claire,

The "SubClass() : BaseClass()" syntax is used only for constructors. It's a
way to indicate which base class constructor to use before entering the
subclass constructor, which is necessary since the base class is
instantiated before any subclass code runs (including its constructor).

For methods, you can simply call the base class method from within the
subclass method. e.g.:

public override void Write(System.IO.BinaryWriter binarywriter)
{
base(binarywriter);
}

You can run other code before/after/instead of the base method call as
desired.

HTH,
Nicole
 
Claire,

The "SubClass() : BaseClass()" syntax is used only for constructors. It's a
way to indicate which base class constructor to use before entering the
subclass constructor, which is necessary since the base class is
instantiated before any subclass code runs (including its constructor).

For methods, you can simply call the base class method from within the
subclass method. e.g.:

public override void Write(System.IO.BinaryWriter binarywriter)
{
base.Write(binarywriter);
}

You can run other code before/after/instead of the base method call as
desired.

HTH,
Nicole
 
Claire said:
I'm having real brain failure today.
I've done this lots of times with constructors but not with virtual methods
and the compiler complains because Ive put the :base(foo) after the function
header.
I want to call the BaseResult class to let it write shared data before I let
the derived class write its own data. What am I doing wrong please.

public abstract class BaseResult

{

public virtual void Write(System.IO.BinaryWriter binarywriter)

{

WriteMyData()

}

}



public class MimicResult : BaseResult

{

public override void Write(System.IO.BinaryWriter binarywriter) :
base(binarywriter) /*compiler complains*/

{

// Do I do something here?


}

}

Yes :)

public override void Write(...)
{
base.Write(...)
etc()
}

David Logan
 
Back
Top