I have an object called BoatShop that contains an array of pointers to objects which are Boats. Boats is a virtual class, and the array is populated with MotorBoats or SailBoats which are derived from the Boats class.
There is a virtual function in the boatclasses, show(), that shows info about the boats. This function is called by the BoatShop when it is listing the contents of the array.
Right now I'm constructing copy constructor and operator= overloading for BoatShop and I've encountered something strange. If I populate a boatshop and copy it to another boatshop, i get segmentation error after the boats in the object is listed. Always after the last one is listed, no matter how many boats there are. So, i'm thinking there is something wrong with the destructor of the boatshop, but when i put a textline in the destructor, it is never shown. So the destructor doesn't seem to be called at the end of main().
There is no segmentation error if the original object is doing the listing. So my next thought is that it must be the copy constructor and/or operator=. By the way, the same error occurs wheter the copy constructor or operator= is called.
Here are a couple of the mentioned functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
BoatShop::BoatShop()
{
maxNrOfBoats = 50;
nrOfBoats = 0;
boats = new Boat*[maxNrOfBoats];
}
BoatShop::~BoatShop()
{
std::cout << "Destruktor";
for (int i = 0; i < nrOfBoats; i++)
delete boats[i];
delete [] boats;
}
BoatShop::BoatShop(const BoatShop &obj)
{
std::cout << "Copy constructor";
maxNrOfBoats = obj.maxNrOfBoats;
nrOfBoats = obj.nrOfBoats;
boats = new Boat*[maxNrOfBoats];
for (int i = 0; i < nrOfBoats; i++)
boats[i] = obj.boats[i];
}
BoatShop & BoatShop::operator=(const BoatShop &right)
{
std::cout << "operator=";
maxNrOfBoats = right.maxNrOfBoats;
nrOfBoats = right.nrOfBoats;
if (nrOfBoats > 0)
delete [] boats;
boats = new Boat*[maxNrOfBoats];
for (int i = 0; i < nrOfBoats; i++)
boats[i] = right.boats[i];
return *this;
}
void BoatShop::showBoats()
{
std::cout << "\n***Båtar***";
for (int i = 0; i < nrOfBoats; i++)
{
std::cout << std::endl << i+1 << ".";
boats[i]->show();
}
}
|
Would be very thankful for any help regarding this.