Rangutang
Rangutang

Reputation: 21

Copy-constructor when using inheritence

I have a problem with a school assignment. I am supposed to create a system that keeps track of contenders in a sporting event. I have a base class contender and two classes that derive from that called Professional and Exerciser.
And then I have a register class that contains a Contender **contenders. And I have to create a copy-constructor for this class but I don't know how to do it.

I thought about something like this

Register::Register(const Register& original)
{
    this->kap = original.kap;
    this->currentAmount = original.currentAmount;
    for (int i = 0; i < this->currentAmount; i++)
    {
        if (Professional* pro = dynamic_cast<Professional*>(this->contenders[i]))
        {
            this->contenders[i] = new Professional(*original.contenders[i]);
        }
        if (Exerciser* pro = dynamic_cast<Exerciser*>(this->contenders[i]))
        {
            this->contenders[i] = new Exerciser(*original.contenders[i]);
        }
    }
    this->initiate(this->currentAmount);
}

Upvotes: 2

Views: 94

Answers (1)

Christophe
Christophe

Reputation: 73627

I understand that contenders is a pointer to an array of pointers.

There are three issues :

  • you need to intialize contenders.
  • the dynamic_cast<> check should use the original object
  • Professional and Exerciser copy constructors are certainly defined as copying objects of type Professional and Exerciser respectively and not Contender.

Here a proposed correction:

Register::Register(const Register& original)
{
    kap = original.kap;
    currentAmount = original.currentAmount;
    contenders = new Contender[currentAmount];  // was missing
    for (int i = 0; i < currentAmount; i++)
    {
        if (Professional* pro = dynamic_cast<Professional*>(original.contenders[i]))
        {
            contenders[i] = new Professional(*pro);  // use the pro instead of contender
        }
        if (Exerciser* exe = dynamic_cast<Exerciser*>(original.contenders[i]))  
        {
            contenders[i] = new Exerciser(*exe);  // use exe instead of contender
        }
    }
    initiate(currentAmount);
}

Three recomendations though:

  • you don't need to use this-> to prefix all object variables. Only in case of ambiguity with local variables of the member function itself.
  • think of using vector instead of a pointer to an array
  • the clone approach proposed in the comments would be a really nice and powerful alternative to your dynamic_cast<> checks

Upvotes: 1

Related Questions