Reputation: 21
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
Reputation: 73627
I understand that contenders
is a pointer to an array of pointers.
There are three issues :
contenders
. dynamic_cast<>
check should use the original objectProfessional
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:
this->
to prefix all object variables. Only in case of ambiguity with local variables of the member function itself. vector
instead of a pointer to an arraydynamic_cast<>
checksUpvotes: 1