0

I'm making a copy-constructor in a class called Registry, which handles an array of pointers of the abstract class Competitor, while Amateur and Professional inherit from Competitor.

How would I go about transferring these to the array of the new Registry-object from the Registry-object I passed in to copy from?

Usually when I'm dealing with a concrete class I would make a for-loop and then do something like:

for(int i=0; i<this->size; i++)
    this->arrOfComp[i] = new Competitor(*original.arrOfComp[i]);

Where original is a parameter of type Competitor.

But I can't allocate Competitor obviously now that it is abstract. And I don't know what type the next object in the array is, so I can't just change it to ... new Amateur(...) or ... new Professional(...), they're not all the same, it's mixed; some are Amateurs, some are Professionals.

Is there some elegant way of making it transfer every object regardless of class so I don't have to write two if-statements and use typeid, dereferencing etc.?

And I know vectors might be the first thing that may come to your mind, but this is an assignment and I don't have a choice.

I checked this one: Copy constructor for abstract class

But it was about Java, I don't know how to make that for C++.

Community
  • 1
  • 1
Jack Of Blades
  • 495
  • 7
  • 16
  • Not an array example but [this method](http://stackoverflow.com/questions/12255546/c-deep-copying-a-base-class-pointer) is what you want. – NathanOliver Dec 06 '16 at 20:59
  • 5
    Your `Competitor` class needs a (pure) virtual function, by convention called `clone`, that returns a pointer to a newly allocated copy of the object. Implement it in each child class. – n. m. could be an AI Dec 06 '16 at 21:00
  • Thanks, I'm reading the linked question, will see if I have any questions after it. – Jack Of Blades Dec 06 '16 at 21:10

0 Answers0