First, what i want to do is to resize a class’ array when it’s full by doing a “object++” but
I got a “Segmentation fault(core dumped)” error when executing a C++ program. The problem is inside the operator++ overloading method. It’s supposed to copy the contain of the first array in a temporary object (the operator= overloading is already done and works well), then to change the height and width of the array, and finally copy again the temporary object inside the object which is returned. When i comment “*this = *tmpPlateau ;” the array is resized but the contain is not copied. the Here is the code :
Plateau& Plateau::operator++() {
// New sizes
int newHauteur = this->height + 2 ;
int newLargeur = this->width + 2 ;
// Tableau temporaire avec le contenu du plateau actuel
Plateau* tmpPlateau = this ;
// Actualisation des dimensions
this->height = newHauteur ;
this->width = newLargeur ;
this->plateau = new Etat*[height] ;
for (int i = 0; i < height; i++) {
plateau[i] = new Etat[width] ;
}
*this = *tmpPlateau ;
return *this ;
}
The operator= overloading method :
Plateau& Plateau::operator=(const Plateau& tab) {
this->plateau = new Etat*[height] ;
for (int i = 0; i < height; i++) {
this->plateau[i] = tab.plateau[i] ;
}
Plateau(height, width) ;
}
I think the problem is twofold.
Firstly,
tmpPlateauis not a separate object. It’s just another pointer to*this:Consequently, the following calls
operator=()with*thisas its argument:I suspect the crash is because your
operator=()doesn’t handle self-assignment correctly.However, the real problem is that
tmpPlateauneeds to hold a copy of the object rather than a pointer to it.Finally, you’d find it much easier to implement your class if you used
std::vectorinstead of an array. This would make it much easier to growplateau.