I am trying to figure out copy constructors for a dynamic array and I am definitely missing something. If I go into the copy constructor routine during debug, the values appear to be correct but they don't percolate up to the newly created object. I'll post a portion of the code below:
Code:
// include header files for the classes that are being used
#include "stdafx.h" //NOTE: THis reference must be added to all cpp files in Visual Studio Express 2013
#include <iostream>
#include <string>
#include <cstdlib>
#include <map>
using namespace std;
const int ARRAY_SIZE_DEFAULT = 32;
class vectorOfInt {
public:
vectorOfInt(); //A no-argument constructor that allocates a 32-element vector
vectorOfInt(int size); //A constructor that takes an initial size as the argument
~vectorOfInt(); //Destructor
//vectorOfInt& operator= (const vectorOfInt& vec);
vectorOfInt(const vectorOfInt& vec);
int size(); // return length
void pushback(int val); // A method pushback that adds an element to the end of the array, resizing if necessary
void pushfront(int val); // A method pushfront that adds an element to the beginning of the array
int getVal(int index); //A method get, taking an index and returning the value at that index
void setVal(int index, int val); //A method set, that takes an index and a value, and sets the value at that index
int& operator[](int index); //assignment operator
private: //variables
int *pa; //Points to the array
int length; //The Number of Elements in an array
int nextIndex; //The Next Highest Index Value. Head value
};
//Copy Constructor
vectorOfInt::vectorOfInt(const vectorOfInt& vec){
int *panew;
int len = vec.length;
panew = new int[len];
memcpy(panew, vec.pa, len);
}
//Constructor with User Input on size
vectorOfInt::vectorOfInt(int size){
//!!!Check to see if size is appropriate value, i.e., > 0
pa = new int[size]; //new provides memory to user-defined number of ints, which pa points to.
//initialize array to zero.
for (int x = 0; x < size; ++x) { pa[x] = 0; }
length = size; //default array size
nextIndex = 0; //nextIndex points to the first address
}//end
int main(){
int lena, lenb, lenc, i;
vectorOfInt a(8);
lena = a.size();
for (i = 0; i < lena; ++i){
a.setVal(i, i+10);
}
vectorOfInt c(a); //copy constructor test
lenc = c.size();
}
The size of c is 0. Values of a were not copied to c, although they appear to do so within the copy constructor routine.