Correct me if I'm wrong:
I understand that when having a class with members that are pointers, a copy of a class object will result in that the pointers representing the same memory address. This can result in changes done to one class object to affect all copies of this object.
A solution to this can be to overload the = operator. Given the example below, with an attempt to create a dynamic array class, why does making changes to MyArray1 change MyArray2:
Array Class:
#include <iostream>
#include <cstdlib>
class Array
{
public:
Array(int N){ //constructor sets size of array
size = N;
arr = new int[N];
}
~Array();
int size; //array elements
int *arr; //dynamic array pointer
//fill array with random values between 1 and 100
void fillArray() {
for (size_t i = 0; i < size; i++)
{arr[i] = std::rand()%100;}
}
//print out array to console
void printArray() {
for (size_t i = 0; i < size; i++)
{ std::cout << arr[i] << " ";}
std::cout << std::endl;
}
//overload = operator
Array &operator=(Array arr2) {
std::swap(size, arr2.size);
std::swap(arr, arr2.arr);
return *this;
}
};
Main.cpp:
#include "Array.h"
#include <iostream>
int main(){
Array MyArray1(8), MyArray2(8);
MyArray1.fillArray();
MyArray2 = MyArray1;
std::cout << "Print out arrays:" << std::endl;
std::cout << "MyArray1: "; MyArray1.printArray();
std::cout << "MyArray2: "; MyArray2.printArray();
std::cout << std::endl;
MyArray1.arr[5] = 1000;
std::cout << "MyArray2: "; MyArray2.printArray();
MyArray1.fillArray();
std::cout << "MyArray2: "; MyArray2.printArray();
return 0;
}
Example output:
Print out arrays:
MyArray1: 41 67 34 0 69 24 78 58
MyArray2: 41 67 34 0 69 24 78 58
MyArray2: 41 67 34 0 69 1000 78 58
MyArray2: 62 64 5 45 81 27 61 91
As seen above, changes made to MyArray1, changes MyArray2. I assume the overloading of = is wrong, but how would I write it correctly?
SOLUTION:
Thanks to Chris Dodd in the comments, I realized it's just to implement a copy constructor like this in my class:
Array(const Array &arr2){
size = arr2.size;
arr = new int[size];
for (size_t i = 0; i < size; i++)
{
arr[i] = arr2.arr[i];
}
}