Simply copying all the values is the default behaviour of the compiler supplied copy contructor. This is known as a "shallow-copy".
More elaborate behaviour is achieved by implementing your own constructor so that the objects (here values) pointed to by your reference are created anew in the copy.
foo::foo(std::istream& s) {
max = s.max;
val = new int;
*val = s->val;
listofVal = new size_t;
*listofVal = s->listofVal;
}
would be one way of achieving that which is known as a "deep copy".
But as one of your members is called listofVal
I rather feel you are doing something other than storing a single value at the memory address it points, in which case you should be holing a counter to the number of elements contained therein, which I will henceforth assume to be the field you call max
. To copy the whole list, your copy constructor would then need to be:
foo::foo(std::istream& s) {
max = s.max;
val = new int;
*val = s->val;
listofVal = new size_t[max];
for (int i = 0; i < max; ++i)
listofVal[i] = s->listofVal[i];
}
Ravi, yes, the copy constructor is a proof of construct and despite breaking the "Rule Of Three" can be implemented before the other two. Here is the assignment operator.
foo& foo::operator=(const foo& matrix) {
if (this != matrix) {
max = matrix.max;
val = new int;
*val = matrix->val;
listofVal = new size_t[max];
for (int i = 0; i < max; ++i)
listofVal[i] = matrix->listofVal[i];
}
}
would be suitabe for object1 = object2;
assignment. I tend towards the copy constructor approach.
The methods need to be members to access the private data so your class should be like
class foo {
///...///As before
foo &operator=(const foo& matrix);
};
Of course it needs a destructor but as it was not explicitly requested I didn't want to answer what wasn't asked.
Following on from the link to the Copy and Swap idiom, when the LHS may already contain data, for robust assignment you might consider:
foo& foo::operator=(const foo& matrix) {
if (this != matrix) {
val = new int;
*val = matrix->val;
size_t* newArray = new size_t[max];
int newMax = matrix.max;
std::copy(matrix.listofVal, matrix.listofVal + max, newArray);
if (listofVal) delete listofVal;
listofVal = newArray;
max = newMax;
}
}
I would add that assigning local objects on the heap can cause memory leaks (if the method breaks before they are assigned to an object responsible for their deletion), but that is just a whole nother layer of parannoia when we have enough to do preserving class integrity.