Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a copy constructor with abstract class

Tags:

c#

oop

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?

like image 948
Michael Avatar asked Sep 16 '25 23:09

Michael


1 Answers

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());
like image 143
Roman Saveljev Avatar answered Sep 18 '25 12:09

Roman Saveljev