Making dervied class from base class

  • Thread starter Thread starter Thomas C
  • Start date Start date
T

Thomas C

I'm looking for the best way to solve the following problem:

public class Foo
{
public void Bar() {}
}

public class Alice : Foo
{
public void Zed() {}
}

Foo foo = new Foo();


What I want to do is to make a new instance of Alice using the data from my
instance of foo like so:

Alice alice = (Alice)foo;
or
Alice alice = new Alice(foo);

Right now, the best solution I have found is to implement a Copy method on
the base class which takes a base class instance and overwrites the local
instance's data with the passed instance's data (e.g. public void Copy(Foo
foo)).

Any better suggestions?



Tom
 
If you have an instance of Foo, there is nothing you can do to promote it to
Alice. It's a Foo, not an Alice!

Now, if you had an instance of Alice, you could treat it as a Foo, since an
Alice is a Foo by definition. But not necessarily the other way around.

Now, if you add a constructor to Alice that takes a Foo, and then it copies
all pertinent information from Foo, then that will work. But you are pretty
much restricted to this type of copy, like in your method.
 
Back
Top