Reputation: 833
I've been trying to create a copy constructor that will work with my program, however, when I run my code it always gives me an error of:
1.) "member 'lengthOfArray' was not initialized in this constructor"
2.) "member 'lengthOfArray' was not initialized in this constructor"
Now I understand what is going on with the above two errors, but the two errors I don't understand are these two:
3.) previous definition is here
4.) redefinition of 'copy'
Here's what I currently have:
simpleVector(const simpleVector& copy) {
simpleVector cy;
simpleVector copy(cy);
}
Now the instructions for what I'm trying to implement are:
your own copy constructor that performs a deep copy, i.e., create a dynamic array and copy elements from the other array that was passed as an argument to the copy constructor.
I've never created a copy constructor before nor have they covered it in class so I'm not to sure exactly how to implement one, but I've searched many sources with not much luck. Is it typical to use a for loop within a copy constructor? Any help with what I'm doing wrong would be appreciated. My entire code:
#include <iostream>
using namespace std;
// simpleVector template
template<class Temp>
class simpleVector {
// private members
private:
Temp* tempPointer;
int lengthOfArray;
public:
// default no-arg constructor
simpleVector() {
tempPointer = NULL;
lengthOfArray = 0;
}
// single argument constructor
simpleVector(int dynamicArray) {
lengthOfArray = dynamicArray;
tempPointer = new Temp[lengthOfArray];
}
// Copy constructor
simpleVector(const simpleVector& copy) {
simpleVector cy;
simpleVector copy(cy);
}
};
Upvotes: 1
Views: 1583
Reputation: 206567
simpleVector(const simpleVector& copy) { // copy decleared here
simpleVector cy;
simpleVector copy(cy); // Being defined here again.
}
That's what the compiler is complaining about.
You need something like:
simpleVector(const simpleVector& copy) : lengthOfArray(copy.lengthOfArray),
tempPointer(new int[copy.lengthOfArray])
{
// Add code to copy the data from copy.tempPointer to this->tempPointer.
}
Upvotes: 2