Reputation: 13
I would not ask this, but after about 5 hours of googling and digging through stack, text books, and youtube videos, I am still stuck. Here is the code I am working with (yes its pretty bad, I am just learning C++) If you make it to the bottom, you will see that I am having trouble getting the copy constructor to actually make another object of type SimpleVector. The last line shows where I am trying to use the copy constructor I created to make mySV2 from mySV, and then demonstrate that it happened by using the print function for the new object.
Thanks again for the help and putting up with my newb question. I honestly believe that feedback is the breakfast of champions (and less crappy coders) so please fire away and know that I will be eternally grateful (or at least for the duration of this class) for your assistance.
template <class T>
class SimpleVector {
public:
T* myarray;
T* temparr;
//constructors
SimpleVector() {
size = 0;
myarray = NULL;
}
SimpleVector(int sz) {
size = sz;
myarray = new T[size];
}
//**** Copy Constructor ****
SimpleVector(const SimpleVector& sv) {
size = sv.size;
dataType = sv.dataType;
temparr = new T[size];
for (int i = 0; i < size; i++) {
temparr[i] = sv.myarray[i];
}
myarray = temparr;
}
};
int main() {
int howMany = 5;
SimpleVector<string> mySV(howMany);
for (int i = 0; i < howMany; i++) {
cout << "Enter item " << (i + 1) << ": ";
cin >> mySV.myarray[i];
}
mySV.print();
template<class T>
SimpleVector<T> mySV2(mySV);
mySV2.print();
return 0;
}
Upvotes: 0
Views: 120
Reputation: 76
There are several issues with your code. The line temparr = new T[size];
creates a memory leak as temparr
is not deleted in the destructor. temparr
is actually not necessary for the copy constructor:
SimpleVector(const SimpleVector& sv){
size = sv.size;
dataType = sv.dataType;
myarray = new T[size];
for (int i = 0; i < size; i++) {
myarray[i] = sv.myarray[i];
}
}
If copying pointers of basic types I would also suggest using the std::copy function from the <utility>
header. You should also consider the rule of three when dealing with copy constructors.
The next issue is found in the main:
template<class T>
SimpleVector<T> mySV2(mySV);
Here you need to specify the type of T
to construct the object. Your class member dataType
cannot specify the type of your newly created object. You should change it to
SimpleVector<std::string> mySV2(mySV);
After adding a void print()
member function and the members size_t size
and std::string dataType
the code executed correctly.
Upvotes: 1