Reputation: 447
I'm trying to copy an Object, which will then be modified, without changing the original object. The relevant classes are:
abstract class Upgrade {}
class Shield: Upgrade
{
public Shield(Shield a) {}
}
The problem is when another class wants to get an "Upgrade" object but the class doesnt know which object it get. For example:
public void AddUpgrade(Upgrade upgrade)
{
for (int i = 0;i<Aliens.Count; i++)
{
Aliens[i].AddUpgrade(What should i put here?);
}
}
i have to use copy constructor because i dont want all the aliens to share the same upgrade reference but the Upgrade is an abstract class, than what should i do?
Upvotes: 4
Views: 2242
Reputation: 2594
You can make Upgrade
cloneable, i.e. add Clone()
to it (every descendant will implement) and it will become something like:
Aliens[i].AddUpgrade(upgrade.Clone());
Upvotes: 6
Reputation: 499132
Instead of copy constructors, consider using a factory - either an abstract factory or some factory methods.
These will allow you as much control over object construction as you wish, without tying you down to the inheritance chain (at least, not much).
Upvotes: 4