I have a class vector210, in which I am trying to create a copy constructor as is outlined below in the sample code below (only part of the complete code).
class vector210 {
public:
int arraySize;
int values[1];
vector210(int array[], int arraySize_){
arraySize = arraySize_;
for(int i = 0;i !=arraySize_;i++){
values[i] = array[i];
}
}
vector210(const vector210 &p){
int values [p.arraySize];
for(int i=0;i<p.arraySize;i++){
values[i] = p.values[i];
};
arraySize = p.arraySize;
};
void print(){
for(int i =0;i <arraySize;i++){
cout << values[i] << endl;
}
if (arraySize ==0){
cout << "Vector is empty." << endl;
}
};
when I run the code in main as:
#include "CST210vector.h"
#include <iostream>
using namespace std;
int main() {
int v[5] = {1,2,3,4,5} ;
vector210 test(v, sizeof(v)/sizeof(*v));
cout << "Array to copy " << endl;
test.print();
cout << "Copied array values:"<< endl;
vector210 testnew = test;
testnew.print();
cout << " " << endl;
cout << testnew.size() << endl;
}
I receive the output to terminal:
Array to copy
1
2
3
4
5
Copied array values:
5
4198189
0
1
2
So somehow it seems like the array that is constructed when the copy constructor is called is wildly different from the array in the old version of the vector210 object, but I am not sure how this is happening. Does anyone have insight as to how this error is coming about? I wish instead for my copy constructor to produce an exact copy of the original array.
values[1]? Is your vector supposed to hold only one element?int values [p.arraySize];does not resizevaluesmember variable, it declared new local variable that shadows member variable.std::vectorinstead of re-inventing it. If you are doing it as an exercise, and you haven't covered dynamic memory allocation yet, you aren't ready to implement it.