I have the following class which is called CoordinatesList. It contains a dynamic array of Coordinates, where each coordinate has 3 integers; x,y, and z. In the class CoordinatesList, I have two different member operator=, I am slightly confused about what is the difference between them?
Will it work the same if I inherited the class coordinates in the class CoordinatesList
class Coordinates {//this is a complete class, do not modify it.
public:
Coordinates() {
x = new int; y = new int; z = new int;
*x = *z = *y = 0;
}
Coordinates(int _x, int _y, int _z) {
x = new int; y = new int; z = new int;
*x = _x;
*z = _y;
*y = _z;
}
Coordinates(const Coordinates& rhs) { // copy constructor
x = new int; y = new int; z = new int;
*x = *(rhs.x);
*y = *(rhs.y);
*z = *(rhs.z);
}
~Coordinates() {
delete x; delete y; delete z;
}
void operator=(const Coordinates& rhs) {//simplified operator=
*x = *(rhs.x);
*y = *(rhs.y);
*z = *(rhs.z);
}
int getx() const { return *x; }
int gety() const { return *y; }
int getz() const { return *z; }
void setx(int _x) { *x = _x; }
void sety(int _y) { *y = _y; }
void setz(int _z) { *z = _z; }
friend ostream& operator<< (ostream& out, const Coordinates& rhs) {
out << "[" << *(rhs.x) << "," << *(rhs.y) << "," << *(rhs.z) << "]" << endl;
return out;
}
private:
int *x, *y, *z;
}; //--------------------------------------------------------------
class CoordinatesList {
public:
/*CoordinatesList & operator=(const CoordinatesList &rhs)
{
if (size != rhs.size)
{
delete[] list;
size = rhs.size;
list = new Coordinates[size];
}
for (int i = 0; i < size; i++)
{
list[i].Coordinates::operator=(rhs.list[i]);
}
return *this;
} */
CoordinatesList operator=(const CoordinatesList & rhs)
{
//check if sizes are differernt
if (size != rhs.size)
{
delete[] list; //this calls ~coordinates
size = rhs.size;
list = new Coordinates[size];
}
//copy content
for (int i = 0; i < size; i++) {
//list[i] = rhs.list[i];
//will work as operator= is defined for Coordinates
list[i].setx(rhs.list[i].getx());
list[i].sety(rhs.list[i].gety());
list[i].setz(rhs.list[i].getz());
}
return *this;
}
private:
Coordinates * list;
int size;
};