Baseclass / Derived class sharing loop code??

M

mickieparis

Hi, is it possible to have a loop in a base class and thru each
iteration of the loop, in the derived class have code that will check
for certain values per each iteration of the loop?

Basically I want to split loop code between the base class and the
derived class. Is this possible? And if so, I’d appreciate some
sample code that shows how this is done. Thanks.

mp
 
P

Peter Duniho

mickieparis said:
Hi, is it possible to have a loop in a base class and thru each
iteration of the loop, in the derived class have code that will check
for certain values per each iteration of the loop?

Basically I want to split loop code between the base class and the
derived class. Is this possible? And if so, I’d appreciate some
sample code that shows how this is done. Thanks.

Anything is possible. The only question is how complicated you want to
make it, and whether that complexity is justified given your goals. :)

You cannot, of course, actually split a single method implementation
across multiple classes. But, you _can_ split the flow of execution of
code in multiple methods across multiple classes. There are a variety
of ways to do that, but in the base-class/derived-class scenario, a very
common pattern is to use virtual methods.

So, for example, you could have something like this:

class Base
{
public void Method(int iMax)
{
for (int i = 0; i < iMax; i++)
{
_LoopBody(i);
}
}

protected virtual void _LoopBody(int i)
{
// default handling here
}
}

class Derived : Base
{
protected override void _LoopBody(int i)
{
// custom handling here
}
}

If it never makes sense to use some "default handling" in the Base
class, you could (and should) make the Base class and the _LoopBody()
method "abstract":

abstract class Base
{
public void Method(int iMax)
{
for (int i = 0; i < iMax; i++)
{
_LoopBody(i);
}
}

protected abstract void _LoopBody(int i);
}

class Derived : Base
{
protected override void _LoopBody(int i)
{
// custom handling here
}
}

If that doesn't suit your needs, you should explain the exact scenario
more clearly and more specifically, so that better, more specific advice
can be provided.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top